Encapsulation

Encapsulation is union data and logic to one unit and hide data from external access. As a result, we have reducing couplings between software components and have more readable and stable code.

Following access modifiers can be applied:

  • private - name is accessible only within class, where it was declared
  • fileprivate - name is accessible only from other entities within the same source file
  • internal - name is accessible for everyone in same module; this is default access
  • public - name is accessible for everyone including other modules
  • open - similar to public, but classes and methods marked as open can be subclassed and overridden respectively in other modules

Swift doesn't offer a protected keyword like other programming languages.

public class SomePublicClass {}
internal class SomeInternalClass {}
fileprivate class SomeFilePrivateClass {}
private class SomePrivateClass {}


public class A {
    fileprivate func someMethod() {}
}

internal class B: A {
    override internal func someMethod() {}
}

You can give a setter a lower access level than its corresponding getter, to restrict the read-write scope. For example, private(set) indicates that property has private setter and default getter, so property will be read-only from outside.

struct TrackedString {
    private(set) var numberOfEdits = 0 
    // you cannot change numberOfEdits from outside of TrackedString
    
    var value: String = "" {
        didSet {
            numberOfEdits += 1         
        }
    }
}