Access Modifiers

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
July 17, 2023

Tutorial: Swift Access Modifiers

In Swift, access control specifies the visibility and availability of different types, methods, properties, and other entities within a module or between modules. It helps you define which parts of your code can be accessed and utilized by other code modules in your project. Let's explore the different access modifiers available in Swift with examples:

Public Access

The public access modifier allows entities to be accessed from any source file within the module or from another module that imports the current module. It provides the highest level of access and is commonly used for public interfaces and frameworks.

Internal Access

The internal access modifier is the default level of access when no access modifier is specified. It allows entities to be accessed within any source file within the module but not from outside the module. It is frequently used for internal implementations and logic.

Fileprivate Access

The fileprivate access modifier restricts the usage of an entity to its own defining source file. It is useful when you want to limit the visibility of an entity to a specific file within the module.

Private Access

The private access modifier is the most restrictive level of access. It limits the visibility of an entity to the enclosing declaration, such as a class or struct. Private entities cannot be accessed from other types or source files within the same module. It is often used to encapsulate implementation details and minimize dependencies.

Examples:


public class PublicClass {
    public var publicProperty: Int
    
    fileprivate var fileprivateProperty: String
    
    internal func internalMethod() {
        // Code here
    }
    
    private func privateMethod() {
        // Code here
    }
}

internal struct InternalStruct {
    private var privateProperty: Bool
}

fileprivate enum FileprivateEnum {
    case caseOne
    case caseTwo
}

private typealias PrivateTypeAlias = Int

In the above example, the PublicClass is accessible from anywhere, even from other modules. The InternalStruct is accessible only within the same module. The FileprivateEnum can only be accessed within the file it is defined in. Lastly, the PrivateTypeAlias is only accessible within the enclosing declaration.

Summary:

The access modifiers in Swift provide control over the visibility and accessibility of entities within a module or between modules. Understanding and utilizing the appropriate access modifier is crucial for designing clean and maintainable codebases. By choosing the right access level, developers can ensure that sensitive information is encapsulated and that public interfaces are well-defined.