Junior — Middle
Can you list and describe the different access levels in the Swift language?
sobes.tech AI
Answer from AI
In Swift, there are several access levels that determine where certain classes, methods, properties, and other code elements can be used:
- open — the most open level. Allows using and inheriting a class or overriding methods from any module.
- public — accessible from any module, but inheritance and overriding are only possible within the module where it is declared.
- internal — accessible only within the current module (default). This means elements are visible in all files of the module but not outside.
- fileprivate — accessible only within the current file.
- private — the strictest level, accessible only within the current declaration (e.g., within a class or struct).
Example:
public class Example {
private var secret = 42
fileprivate func helper() {}
internal func doSomething() {}
public func expose() {}
open func overrideMe() {}
}
Choosing the access level helps control encapsulation and protect internal implementation details.