Sobes.tech
Junior

How is encapsulation implemented in Swift?

sobes.tech AI

Answer from AI

Encapsulation in Swift is implemented using access levels and structures/classes.

Access Levels:

  • open: The highest level. Accessible from any module and any file within that module. Classes marked as open can be subclassed, and methods can be overridden.
  • public: Accessible from any module and any file within that module. Unlike open, classes cannot be subclassed outside the module, and methods cannot be overridden.
  • internal: The default access level. Accessible only within its defining module.
  • fileprivate: Accessible only within the file where it is defined.
  • private: The lowest level. Accessible only within its defining declaration (structure, class, enumeration, etc.).
// Example of using access levels
open class OpenClass { // Accessible and inheritable from any module
    public var publicProperty: Int = 0 // Accessible from any module
    internal var internalProperty: String = "" // Accessible only within the module
    fileprivate var fileprivateProperty: Double = 0.0 // Accessible only within the file
    private var privateProperty: Bool = false // Accessible only within OpenClass
}

class InternalClass { // Default is internal
    // ...
}

Structures and Classes:

They serve as containers for data (properties) and behavior (methods). Access levels are applied to properties and methods, controlling their visibility and accessibility from outside. This allows hiding internal implementation details and providing only the necessary interface for interaction.

// Example of encapsulation using a private property
struct BankAccount {
    private var _balance: Double = 0.0 // Private property

    var balance: Double { // Public read-only access
        return _balance
    }

    mutating func deposit(amount: Double) {
        if amount > 0 {
            _balance += amount
        }
    }

    mutating func withdraw(amount: Double) {
        if amount > 0 && amount <= _balance {
            _balance -= amount
        }
    }
}

// Usage
var account = BankAccount()
account.deposit(amount: 100) // Access to deposit method
// account._balance = 200  // Error: _balance is private
print(account.balance) // Access to balance property

Thus, encapsulation in Swift is achieved by using access levels to restrict the visibility of internal implementation details and structures/classes to group data and behavior. This promotes information hiding, modularity, and simplifies maintenance.

How is encapsulation implemented in Swift? — iOS - sobes.tech