Swift Access Control Example

1. Introduction

Swift provides five different access levels to entities like classes, variables, functions, etc.:

1. open and public - Accessible from any source file in the defining module or any module that imports that module.

2. internal - Accessible only from within the defining module (default access level).

3. fileprivate - Accessible only from within the defining source file.

4. private - Accessible only from the immediate enclosing declaration.

2. Source Code Example

// Defining a class with different access levels
class AccessControlExample {
    public var publicVar = "I can be accessed from outside the module too!"
    internal var internalVar = "I can be accessed within the same module (default)."
    fileprivate var fileprivateVar = "I can be accessed within this source file."
    private var privateVar = "I can be accessed only from this declaration."

    func demonstrateAccess() {
        print(privateVar) // Accessible because it's in the same declaration
        print(fileprivateVar) // Accessible because it's in the same source file
    }
}

let example = AccessControlExample()

print(example.publicVar)      // Accessible
print(example.internalVar)    // Accessible
// print(example.fileprivateVar)  -> This will raise a compilation error outside the `AccessControlExample` class
// print(example.privateVar)     -> This will raise a compilation error outside the immediate declaration

Output:

I can be accessed from outside the module too!
I can be accessed within the same module (default).

3. Step By Step Explanation

1. We've defined a class AccessControlExample with properties of different access levels: publicVar, internalVar, fileprivateVar, and privateVar.

2. The function demonstrateAccess within the class can access all properties because:

- privateVar is within the same declaration.- fileprivateVar is within the same source file.- Others (publicVar and internalVar) are accessible regardless.

3. Outside the class, while creating an instance of AccessControlExample, we can access the publicVar and internalVar without issues. However, trying to access fileprivateVar and privateVar would result in compilation errors.

Using appropriate access levels in Swift can help encapsulate the internal workings of a class or structure, thereby promoting modular code and protecting the integrity of data structures.


Comments