skip to content

In Swift, when are a property's willSet and didSet observers called, and when does Swift skip them?

level: middleimportance: must knowfreq 60%

answer

  1. just before, just after
  2. newValue and oldValue
  3. even when nothing changed
  4. the type's own initializer

basics

~20 s

willSet runs just before a new value is stored and didSet right after, on every assignment outside initialization, even when the value is unchanged. They are not called while a type's own initializer sets the property.

solid answer

~40 s

`willSet` receives the incoming value as `newValue` (a constant) and runs before storage changes; `didSet` receives the previous value as `oldValue` and runs after. Both run on **every** set, including assigning the same value, and when the property is passed `inout`, because of copy-in copy-out. They do **not** run while a class or struct sets its own properties in its own initializer; a subclass initializer that assigns an inherited property after `super.init` does trigger the superclass's observers. Assigning the property inside its own `didSet` replaces the stored value without calling the observers again. You can observe stored properties you declare and, by overriding, inherited stored or computed ones; a computed property you declare reacts in its setter instead, and combining the two is the error "'didSet' cannot be provided together with a getter".

code

swift · 24 lines
swift
class Thermostat {
    var targetCelsius: Double {
        willSet { print("will change to \(newValue)") }
        didSet {
            if targetCelsius > 30 { targetCelsius = 30 }   // no second didSet
            print("changed from \(oldValue) to \(targetCelsius)")
        }
    }
    init(targetCelsius: Double) {
        self.targetCelsius = targetCelsius   // observers NOT called
    }
}

final class OfficeThermostat: Thermostat {
    init() {
        super.init(targetCelsius: 20)
        targetCelsius = 22                   // superclass observers ARE called
    }
}

let home = Thermostat(targetCelsius: 19)     // prints nothing
home.targetCelsius = 19                      // same value: both observers run
home.targetCelsius = 45                      // clamped to 30 inside didSet
_ = OfficeThermostat()

go deeper

for a junior

Recall the order, willSet then storage then didSet, and the default parameter names newValue and oldValue.

for a middle

Explain the initialization rule, the subclass exception after super.init, same-value assignments, inout write-back, and why assigning inside didSet does not recurse.

for a senior

Use observers deliberately: factor init-time logic into a method, guard against unchanged values when the reaction is costly, and avoid surprising side effects on inout passes.

for a principal

Weigh observers against explicit methods for team code: observers hide work behind assignment syntax, so set a norm for when reacting implicitly is clearer than calling an update method.

## The two observers A **property observer** is code attached to a stored property that runs when the property is set. Swift has two, and you can declare either or both: - `willSet` runs **just before** the new value is stored. It receives the incoming value as a constant named `newValue`, or a name you choose with `willSet(newTarget)`. Because the parameter is a constant, `willSet` cannot change what is about to be stored. - `didSet` runs **immediately after** the new value is stored. It receives the previous value as `oldValue`, or a name you choose, and can read the property itself to see the new value. Observers can also be attached to global and local stored variables, where the language reference calls them stored variable observers; the rules are the same. ## When they run Observers fire on every **set** that happens outside an initialization context: 1. A plain assignment, `home.targetCelsius = 21`. 2. An assignment of the **same** value. Swift does not compare old and new; if you only care about real changes, compare `oldValue` with the new value yourself (which requires the type to be `Equatable`). 3. Passing the property as an `inout` argument. The function receives a copy and the result is written back when it returns, so both observers run after the function body, even if the function changed nothing. 4. Mutating part of a value-typed property, such as appending to an array or changing a field of a nested struct. That is a write to the whole property; the material on persistence in `didSet` works through what this costs. Reading a property never calls its observers, and neither does the first-access initialization of a `lazy` property; a later assignment to it does. ## When they are skipped The initialization rule is the one most often asked: | Situation | Observers called? | |---|---| | A type's initializer assigns its own property | No | | A default value in the declaration | No | | A subclass initializer assigns an inherited property after `super.init` | Yes, the superclass's observers | | Any assignment after initialization | Yes | | Assigning the property inside its own `didSet` | No second call | The reason is that initialization is establishing the first value, not changing an existing one, and an observer might touch other properties that are not set yet. If the logic must also run for the initial value, call it explicitly at the end of the initializer, typically a small method that both the initializer and the observer use. ## Assigning inside didSet If `didSet` assigns the property again, for example to clamp it, the new assignment replaces the value that was just stored and the observers are **not** re-entered. Clamping in `didSet` is safe and does not recurse: ```swift var targetCelsius: Double { didSet { if targetCelsius > 30 { targetCelsius = 30 } } } ``` `willSet` sees the unclamped `newValue`; anything reading the property afterwards sees the clamped one. ## Where observers can be attached - **Stored properties you declare**, `var` only, including `lazy var`. - **Inherited properties, stored or computed**, by overriding them in a subclass. That is how a subclass reacts to a superclass's computed property; the lesson on subclassing and overrides covers the override rules. - **Not a computed property you declare yourself**: put the reaction in its `set` accessor. Writing both a getter and `didSet` is the error "'didSet' cannot be provided together with a getter". - **Not a property whose getter is `async` or `throws`**: such a property is read-only, and the compiler rejects the observer. ## Observers or a computed setter? Observers and a computed property over private backing storage can express similar behaviour, and the choice is worth stating in an interview: - An observed property **is** the storage: it appears in the memberwise initializer of a structure, and the value is stored before `didSet` runs. - `willSet` cannot alter or reject the incoming value. To validate or transform before anything is stored, use a computed property whose setter writes a private stored property, or correct the value afterwards by reassigning in `didSet`. - A computed setter runs during initialization too if the initializer assigns through it, once every stored property has a value, whereas observers do not run there; that difference decides many such choices. ## Using them well - Keep observers cheap and side-effect-light: they run on every write, including writes you did not expect, such as `inout` passes. - Prefer `didSet` for reacting (updating a label, posting a change, validating) and keep `willSet` for the rare case that needs the old state before it disappears. - Do not rely on observers for invariants that must hold right after initialization; they will not have run.

  • How do you run a didSet's logic for the value set in the initializer as well?
    Observers do not run while a type's own initializer assigns its properties, so move the reaction into a method, for example applyTarget(), call it from didSet, and call it once more at the end of the initializer, after every stored property has a value.
  • Can you add didSet to a computed property you declare?
    No. A computed property you declare already has a setter, which is where the reaction belongs; adding an observer is the compile error "'didSet' cannot be provided together with a getter". A subclass can, however, add observers to a computed property it inherits by overriding it.
  • Why do both observers run when an observed property is passed as an inout argument?
    inout is copy-in copy-out: the function works on a copy, and the value is written back to the property when the function returns. That write-back is a set, so willSet and didSet run even if the function did not change the value.

  • didSet only fires when the new value differs from the old one.
  • Assigning the property inside its own didSet recurses forever.
  • Observers run when the type's own initializer assigns the first value.
  • willSet can change the incoming value by assigning to newValue.
  • You can attach didSet to a computed property you declare yourself.