skip to content

A Swift property with a didSet observer is passed inout to a function that increments it three times. How many times does didSet fire, and why?

level: seniorimportance: should knowfreq 32%

answer

  1. not a pointer to the property
  2. call by value result
  3. getter at call, setter at return
  4. one write-back, one observer call
  5. by-reference is only an optimisation

basics

~20 s

Once. Swift's inout is copy-in copy-out: the property's value is read when the call starts, the function mutates a temporary copy, and the final value is assigned back once when it returns, so the setter and didSet run a single time.

solid answer

~40 s

`didSet` fires **once**, after the function returns, with `oldValue` equal to the value before the call. The reference manual defines `inout` as **copy-in copy-out** (call by value result): the argument is copied in when the call starts, the body changes the copy, and the copy is assigned back to the original when the function returns. For a computed property or a property with observers that means the getter runs as part of the call and the setter — and with it `willSet`/`didSet` — runs once as part of the return. For a plain stored variable the compiler may pass the memory location directly, which is called call by reference, but that is an optimisation that must be indistinguishable from the model, so correct code never depends on it.

code

swift · 26 lines
swift
struct Draft {
    var retries = 0 {
        didSet { print("didSet: \(oldValue) -> \(retries)") }
    }
}

struct Box {
    var storage = 10
    var doubled: Int {
        get { print("get"); return storage * 2 }
        set { print("set \(newValue)"); storage = newValue / 2 }
    }
}

func bumpThreeTimes(_ value: inout Int) {
    value += 1
    value += 1
    value += 1
    print("inside: \(value)")
}

var draft = Draft()
bumpThreeTimes(&draft.retries)   // inside: 3, then didSet: 0 -> 3

var box = Box()
bumpThreeTimes(&box.doubled)     // get, inside: 23, set 23

go deeper

for a junior

Remember the answer: observers fire once, after the function returns, because inout writes the final value back a single time.

for a middle

Walk through the three steps of copy-in copy-out and say where the getter, setter and observers run for computed and observed properties.

for a senior

Diagnose missing observer calls in real code, explain call by reference as a permitted optimisation, and connect the model to the ban on overlapping access.

for a principal

When a type relies on observers for logging or invariants, set the expectation that in-place mutation through inout reports one change, not each step.

## The scenario A settings struct counts retries and logs every change with a property observer. A helper bumps the count through an `inout` parameter: ```swift struct Draft { var retries = 0 { didSet { print("didSet: \(oldValue) -> \(retries)") } } } func bumpThreeTimes(_ value: inout Int) { value += 1 value += 1 value += 1 } var draft = Draft() bumpThreeTimes(&draft.retries) // prints "didSet: 0 -> 3" once ``` A developer who pictures `inout` as a pointer expects three log lines, one per increment. Built with the Swift 6.4 toolchain, the program prints one. ## The model: copy-in copy-out The reference manual spells out how in-out parameters are passed: 1. When the function is called, the value of the argument is copied. 2. In the body of the function, the copy is modified. 3. When the function returns, the copy's value is assigned to the original argument. This is **copy-in copy-out**, also called **call by value result**. The manual then gives the exact consequence this question probes: when a computed property or a property with observers is passed as an in-out parameter, "its getter is called as part of the function call and its setter is called as part of the function return." Observers hang off the setter, so `willSet` and `didSet` run once, at the write-back, and `oldValue` is the value from before the call. The same holds for a computed property: passing `&box.doubled` calls the getter once before the body runs and the setter once after it, however many times the body assigns. ## Where call by reference comes in For a value **stored at a physical address** — a local `var`, a stored property without observers, an array element — the compiler is allowed to use the same memory location inside and outside the function. The manual names this **call by reference** and describes it as an optimisation that "satisfies all of the requirements of the copy-in copy-out model while removing the overhead of copying." It then gives the rule that matters for code review: write code against the copy-in copy-out model and never depend on the optimisation. | Argument passed with `&` | What happens at the call | What happens at the return | |---|---|---| | Local `var` or plain stored property | may share memory directly (optimisation) | nothing observable beyond the new value | | Stored property with `willSet`/`didSet` | value read into a temporary | setter runs once; observers fire once | | Computed property | getter runs once | setter runs once with the final value | | Array element `&items[0]` | element accessed through the subscript | element written back when the call ends | ## What goes wrong when you think "pointer" The pointer mental model leads to three concrete mistakes: - **Expecting per-step observer calls.** Logging, validation or UI updates inside `didSet` see only the final value. An intermediate value that violates an invariant never reaches the observer — good for consistency, surprising if you wanted an audit trail of each step. - **Expecting the caller to see the change mid-call.** Under the model, the original is updated when the function returns. Trying to watch the original from inside the call is not just unreliable: reading or writing the same variable while it is passed in-out is an overlapping access, which Swift's exclusivity rules forbid. - **Trying to keep the parameter.** Because the value only exists for the duration of the call, an escaping closure cannot capture an `inout` parameter; the compiler reports `escaping closure captures 'inout' parameter`. ## Diagnosing it in practice When an observer fires fewer times than expected: 1. Check whether the property reaches the function through `&` — directly, or via a helper that takes `inout`. 2. Remember that a `mutating` method called on a property is also a single write-back of the whole value, so its observers fire once at the end of the call as well. 3. Expect the opposite surprise too: the book notes that observers on a property passed in-out are **always** called, because the value is always written back — even when the function only reads it. 4. If you genuinely need each step observed, perform the steps as separate assignments at the call site, or return a value per step instead of mutating in place. The practical rule: think of `inout` as "the function gets a temporary it may change, and the result is stored back once", not as "the function gets my variable's address".

  • If Swift may pass a stored variable to an inout parameter by reference, why does the language insist on the copy-in copy-out model?
    Because the optimisation is only allowed when nobody can tell the difference. The reference manual calls call by reference an optimisation that satisfies all the requirements of copy-in copy-out, and tells you to write code against the model so it behaves correctly with or without the optimisation. Swift's exclusivity rules forbid the overlapping accesses that could otherwise reveal which one happened.
  • How does a mutating method called on a property with didSet compare with passing that property inout?
    It behaves the same way. Calling a mutating method on a stored property works like passing it in-out: `draft.settings.reset()` reads `settings`, runs the method against it, and writes the whole value back once; the `didSet` on `settings` fires once at the end, however many fields the method changed.

It is like checking a form out of a filing office: you take a copy home, change it three times, and file it back once — the office logs a single update, from the original to the final version.

  • didSet fires once for every assignment the function makes
  • inout passes the property's memory address in every case
  • The caller's property already holds intermediate values during the call
  • A computed property cannot be passed as an inout argument
  • Call-by-reference behaviour is guaranteed, so code may rely on it