OOPJuniorMCQ
What is encapsulation, and how does Swift's access control support it?
Test your knowledge:
Explanation & Code
Answer: Encapsulation means bundling data with the operations that act on it, and restricting direct access to that data so internal invariants can't be broken from outside. Swift enforces this through access control levels rather than getter/setter conventions.
| Level | Visibility |
|---|---|
private | Within the enclosing declaration (and extensions in the same file) |
fileprivate | Anywhere in the same file |
internal (default) | Anywhere in the same module |
public | Any module, but not overridable/subclassable outside |
open | Any module, including override/subclass |
class BankAccount {
private(set) var balance: Decimal = 0 // readable outside, writable only inside
func deposit(_ amount: Decimal) {
guard amount > 0 else { return } // invariant protected here
balance += amount
}
}
let account = BankAccount()
account.deposit(100)
// account.balance = 1_000_000 // ❌ compile error — can't bypass deposit()
Rate your understanding: