Junior — Middle
Explain the concept of access modifiers and their internal implementation.
sobes.tech AI
Answer from AI
Access modifiers for types with restricted access to their internal implementation are a concept of encapsulation, which allows hiding the implementation details of a type (such as a class or structure) from external code. In iOS (Swift), this is achieved through access levels such as private, fileprivate, internal, public, and open.
For example, if a class has properties or methods declared as private, they are only accessible within that class and not visible outside. This helps protect the internal state of the object from direct modification and controls interaction through a public interface.
Example:
class BankAccount {
private var balance: Double = 0.0
func deposit(amount: Double) {
balance += amount
}
func getBalance() -> Double {
return balance
}
}
let account = BankAccount()
account.deposit(amount: 100)
print(account.getBalance()) // 100
// account.balance = 500 // Error: 'balance' is inaccessible due to 'private' access level
Thus, access restriction helps maintain data integrity and simplifies code maintenance.