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:
openandpublic— accessible from any moduleinternal(default) — accessible within the current modulefileprivate— accessible within the current fileprivate— 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.