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.
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.
Swift code does not run on this page. Save your edited code as main.swift on your own computer, compile it with swiftc and run it.
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)finalclassWallet {var coins = 0}
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.