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.

LevelVisibility
privateWithin the enclosing declaration (and extensions in the same file)
fileprivateAnywhere in the same file
internal (default)Anywhere in the same module
publicAny module, but not overridable/subclassable outside
openAny 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:

Related Questions

Browse all OOP questions

Ready to practice more OOP?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.