Access Specifiers in Swift
Swift provides several access control levels to restrict access to parts of your code from other code in different source files and modules. Here are the main access specifiers:
- Private:
- Restricts access to the enclosing declaration and to extensions of that declaration within the same file.
- Use private to hide implementation details within a single class or struct.
Example:
Swift
class MyClass {
private var privateProperty = 0
}
2. Fileprivate:
- Restricts access to the entire file in which it is declared.
- Use fileprivate when you need to share code within the same file but not outside of it.
Example:
Swift
class MyClass {
fileprivate var fileprivateProperty = 0
}
3. Internal (default):
- Allows access within the same module but not from outside the module.
- This is the default access level if you do not specify one.
Example:
Swift
class MyClass {
var internalProperty = 0
}
4. Public:
- Allows access from any module, but the class or method cannot be subclassed or overridden outside the module.
- Use public for APIs that are intended to be used by other modules.
Example:
Swift
public class MyClass {
public var publicProperty = 0
}
AI-generated code. Review and use carefully. More info on FAQ.
5. Open:
- Similar to public, but also allows the class or method to be subclassed and overridden outside the module.
- Use open for classes and methods that are designed to be extended.
Example:
Get Rahul Singh’s stories in your inbox
Join Medium for free to get updates from this writer.
Swift
open class MyClass {
open var openProperty = 0
}
6. Fileprivate vs Private
- Private: Limits access to the enclosing declaration and its extensions within the same file.
- Fileprivate: Limits access to the entire file in which it is declared.
Example:
Swift
class MyClass {
private var privateProperty = 0
fileprivate var fileprivateProperty = 0
}
extension MyClass {
func accessPrivate() {
print(privateProperty) // Accessible
}
}
class AnotherClass {
func accessFileprivate() {
let instance = MyClass()
print(instance.fileprivateProperty) // Accessible
// print(instance.privateProperty) // Not accessible
}
}
In this example, privateProperty is only accessible within MyClass and its extensions, while fileprivateProperty is accessible within the entire file12.
7. Open vs Public
- Public: Allows access from any module, but the class or method cannot be subclassed or overridden outside the module.
- Open: Allows access and also permits the class or method to be subclassed and overridden outside the module.
Example:
Swift
public class PublicClass {
public func publicMethod() {}
}
open class OpenClass {
open func openMethod() {}
}
In this example, PublicClass and its publicMethod can be accessed from any module, but cannot be subclassed or overriddenOpenClass and its openMethod can be accessed, subclassed, and overridden from any module34.






