Sobes.tech
Junior — Middle

Kuidas kasutatakse inkapsuleerimise mehhanismi Swift keeles?

sobes.tech AI

Vastus AI-lt

In Swift, the encapsulation mechanism is implemented through access levels to properties and methods of classes, structures, and enumerations. The main access levels are:

  • open and public — accessible from any module
  • internal (default) — accessible within the current module
  • fileprivate — accessible within the current file
  • private — accessible only within the current declaration

This allows hiding internal implementation details and providing only the necessary interface for interaction with the object.

Example:

class BankAccount {
    private var balance: Double = 0.0

    func deposit(amount: Double) {
        guard amount > 0 else { return }
        balance += amount
    }

    func getBalance() -> Double {
        return balance
    }
}

let account = BankAccount()
account.deposit(amount: 100)
print(account.getBalance()) // 100
// account.balance is not accessible from outside

Thus, encapsulation helps protect data and control access to it.