Tools
Log in
English

Learn to codeSwift

Swift encapsulation

Based on Swift 6.4

Swift private(set), willSet, didSet, computed properties and throws, by example.

In one line

Hiding an object’s values so nobody can change them freely, and allowing changes only through methods you define. Swift can close reading and writing separately (private(set)).

Why you need it

If the balance is a plain var, one line such as balance -= 400_000 anywhere in the app makes it negative. A withdrawal rule in a method does nothing when code skips the method.

Hide the writing side inside the class, and the balance can change only through deposit and withdraw. Checks, logging and error reporting then live in those two places plus didSet.

Everyday picture

Think of a bank counter. Anyone can look at the balance screen, but only the clerk moves money in the vault. The clerk writes every move in a ledger (didSet) and hands back a refusal slip (throw) when someone asks for more than the balance.

The bug you get when anyone can change a property

let acct = Account(owner: "Doyun")acct.balance = 150_000acct.balance -= 400_000acct.owner = ""print("[\(acct.owner)] \(acct.balance) won") final class Account {    var owner: String    var balance = 0     init(owner: String) {        self.owner = owner    }}

When you run it

[] -250000 won

balance and owner are plain vars, so outside code edits them directly. Taking 400,000 out of an account that holds 150,000 is not stopped, and the balance ends at -250,000.

The owner becomes an empty string too. Spread lines like these over a few files and finding the one that broke the balance is hard.

Example code

main.swift · 65 lines
import Foundation let acct = Account(owner: "Doyun")acct.memo = "  rent money  "do {    try acct.deposit(150_000)    try acct.withdraw(400_000)    print("not printed")} catch AccountError.notEnough(let short) {    print("short by \(short) won")} catch {    print("other error: \(error)")}do {    try acct.withdraw(60_000)} catch {    print("other error: \(error)")}print("\(acct.memo): \(acct.balance) won, low: \(acct.isLow)")print("history: \(acct.history)") enum AccountError: Error {    case notPositive    case notEnough(short: Int)} final class Account {    let owner: String    private(set) var history: [Int] = []    private(set) var balance = 0 {        willSet {            print("balance \(balance) -> \(newValue)")        }        didSet {            history.append(balance - oldValue)        }    }    var memo = "" {        didSet {            memo = memo.trimmingCharacters(in: .whitespaces)        }    }    var isLow: Bool {        balance < 100_000    }     init(owner: String) {        self.owner = owner    }     func deposit(_ amount: Int) throws {        guard amount > 0 else {            throw AccountError.notPositive        }        balance += amount    }     func withdraw(_ amount: Int) throws {        let short = amount - balance        guard short <= 0 else {            throw AccountError.notEnough(short: short)        }        balance -= amount    }}

When to use it

  • Reading is fine but changing needs rules (private(set) plus methods)
  • Something must happen on every change (logging, refreshing the screen): didSet
  • A request cannot be done and the caller needs to know why: throws with an error enum

Inside willSet the new value is called newValue; inside didSet the old one is oldValue. Neither runs for the value assigned in init.

A computed property (var isLow: Bool { ... }) has no storage, so it can never fall out of step with other values.

Common mistakes

Leaving the setter wide open

With var coins, anyone can store -30. Keep reading open, close writing with private(set), and check values inside a method whose name says why the value changes (add).

Wrong

let wallet = Wallet()wallet.coins = -30print(wallet.coins) final class Wallet {    var coins = 0}

When you run it-30

Fixed

let wallet = Wallet()wallet.add(-30)print(wallet.coins) final class Wallet {    private(set) var coins = 0     func add(_ amount: Int) {        if amount > 0 {            coins += amount        }    }}

When you run it0

Assigning to a private(set) property from outside

Reading is allowed, but the setter exists only inside the class, so the compiler refuses. Go through deposit, which has the checks. try? is a short form that turns a thrown error into nil.

Wrong

let acct = Account(owner: "Eun")acct.balance = 1_000_000

What the Swift compiler sayserror: cannot assign to property: 'balance' setter is inaccessible

Fixed

let acct = Account(owner: "Eun")try? acct.deposit(1_000)print(acct.balance)

When you run itbalance 0 -> 1000 1000

Calling a throws method without try

A throws method announces that it may throw, so the caller must write try and decide where errors go with do and catch. Unlike Java you do not list which errors, but the fact that it can throw is always visible.

Wrong

let acct = Account(owner: "Eun")acct.deposit(500)

What the Swift compiler sayserror: call can throw but is not marked with 'try'

Fixed

let acct = Account(owner: "Eun")do {    try acct.deposit(-500)} catch {    print("refused: \(error)")}

When you run itrefused: notPositive

Check yourself

Question 1

What is isLow on a brand-new account?

let a = Account(owner: "Jin")print(a.isLow)

Show the answer

Answer: 1. true The balance is 0, so balance < 100_000 is true. A computed property is worked out fresh on every read, from the very start.

Question 2

memo is set with spaces around it. What is printed?

let a = Account(owner: "Jin")a.memo = "  car  "print("[\(a.memo)]")

Show the answer

Answer: 2. [car] The didSet on memo trims the spaces right after the assignment, so reading it gives car.

Questions people ask

What does private(set) mean?

It sets different reach for reading and writing. private(set) var balance can be read by anyone, but only code inside the type can change it. It is often paired, as in public private(set).

When do willSet and didSet run?

willSet runs right before a stored property changes and didSet right after. Inside willSet the new value is newValue; inside didSet the old value is oldValue. Neither runs for the first value set in init.

What type should I throw?

An enum that conforms to Error is common. Each case names a situation, and values such as the missing amount ride along as associated values. Callers catch each case separately.