A Swift subclass overrides an inherited `baseURL` property to add `willSet` and `didSet`; what can a property override change, and when do these observers run?
answer
- name and type, never storage
- read-only may become read-write
- no observers on let
- nested willSet/didSet order
- after super.init()
basics
~10 sA Swift property override supplies a getter (and setter) or adds willSet/didSet, never new storage. Its observers wrap the superclass's own observers and also fire when a subclass initializer sets the property after super.init().
solid answer
~40 sAn override states the property's name and type and then either supplies a getter and optional setter, or adds `willSet`/`didSet`. It never adds storage: `override var x = 1` is "cannot override with a stored property". You may turn a read-only property into a read-write one, but not the reverse. You cannot observe a `let` or a read-only computed property, and you cannot combine a setter override with observers. On assignment, the subclass's `willSet` runs, then the superclass's `willSet`, store and `didSet`, then the subclass's `didSet`. Observers are skipped while a class sets its own properties in its own init. In a subclass initializer, setting `baseURL` after `super.init()` fires the observers, which surprises code whose `didSet` writes to disk or reloads a client.
code
swift · 21 linesclass APIClient {
var baseURL: String = "https://a.example" {
willSet { print("base willSet") }
didSet { print("base didSet") }
}
init() { baseURL = "https://init.example" } // no observers fire here
}
class StagingClient: APIClient {
override var baseURL: String {
willSet { print("sub willSet") }
didSet { print("sub didSet") }
}
override init() {
super.init()
baseURL = "https://staging.example" // both levels' observers fire
}
}
let client = StagingClient()
client.baseURL = "https://x.example"go deeper
Recall that a property override uses override var with the name and type, and can add willSet or didSet to an inherited property.
Explain getter/setter overrides versus observer overrides, why read-only can widen to read-write but not narrow, and why let properties cannot be observed.
Predict the nested observer order and the subclass-init case. Spot a didSet with side effects firing from a subclass initializer, or an oldValue read triggering an expensive inherited getter.
Treat observable inherited properties as part of the base class's contract. If subclasses react to them, changing how the base sets them becomes a breaking change for every subclass.
## Two ways to override a property A Swift subclass can override any inherited **instance or type property** in one of two ways. In both cases it writes `override var`, the property's **name and type**, and an accessor body. The subclass never knows whether the superclass stored the value or computed it. It only knows the name and the type. 1. **A custom getter, and optionally a setter.** `override var description: String { super.description + " (staging)" }` replaces how the value is produced. Inside it, `super.description` reads the inherited value. 2. **Observers.** `override var baseURL: String { didSet { ... } }` keeps the inherited storage or accessors and adds `willSet` and/or `didSet` around them. What you cannot write is a **stored** override. `override var timeout = 60.0` fails with "cannot override with a stored property 'timeout'". Storage belongs to the class that declared the property. ## The rules the compiler enforces | Override attempt | Swift 6.4 result | |---|---| | Getter on a read-only inherited property | allowed | | Getter and setter on a read-only inherited property | allowed: read-only becomes read-write | | Getter only on a read-write inherited property | error: cannot override mutable property with read-only property | | Observers on an inherited `let` | error: cannot observe read-only property 'id'; it can't change | | Observers on an inherited read-only computed property | the same "cannot observe read-only property" error | | Getter on an inherited `let` | error: cannot override immutable 'let' property with the getter of a 'var' | | Setter **and** `didSet` in one override | error: 'didSet' cannot be provided together with a getter | | Narrower type on a mutable property | error: cannot override mutable property of type 'Base' with covariant type 'Sub' | | `override var x = 1` (stored) | error: cannot override with a stored property | Three of these rows explain most interview follow-ups: - **Widening is allowed, narrowing is not.** A subclass may promise more than its superclass, read-write where the superclass was read-only, but never less. Code holding a superclass reference may assign to a read-write property. - **Observing needs a setter.** A value that cannot be set never changes, so there is nothing to observe. - **Setter or observers, not both.** If you already own the setter, put the observing code in the setter. ## Observer order across the hierarchy When a subclass adds observers to a property whose superclass also has observers, one assignment runs both levels, nested. The subclass's `willSet` runs first. The subclass then sets the value through the superclass, so the superclass's `willSet`, the store, and the superclass's `didSet` run next. The subclass's `didSet` runs last. If the subclass's `didSet` reads `oldValue`, Swift calls the inherited getter before the set to capture it, so an expensive superclass getter can run more often than you expect. ## Observers during initialization Within a class's own initializer, assignments to its own properties do **not** call that class's observers. `APIClient.init` setting `baseURL` prints nothing. A subclass initializer is different. Once `super.init()` has returned, assigning an inherited property fires the observers, the superclass's and the subclass's override alike. The book states this for superclass observers, and the Swift 6.4 compiler runs both levels in the example. If those observers write to disk or post notifications, a subclass init that adjusts inherited state triggers them, sometimes before the subclass has finished setting up. ## Production checklist - Prefer an observer override when you only need to react, and a getter/setter override when you must change the value. - Never assume a superclass observer is skipped because you overrode the property. - Watch for `oldValue` in an override's `didSet` when the inherited getter does real work. - Set inherited properties in a subclass init only when their observers are safe to run at that point.
- Why does a `didSet` override that reads `oldValue` call the inherited getter an extra time?To supply `oldValue`, Swift must read the current value before setting the new one, so it calls the inherited getter first. Without `oldValue`, the new value is set without that extra call. When the superclass's property is computed and expensive or has side effects, referring to `oldValue` in a subclass observer adds one more call per assignment.
- Can a subclass override a read-write `var payload: Payload` as `ProfilePayload`, a subclass of `Payload`?Not while it stays mutable. Swift rejects it with "cannot override mutable property ... with covariant type", because a caller holding the superclass type could assign a value of the broader type. A read-only property may narrow its type, since it is only ever read.
- A subclass can override a property with its own stored property
- Overriding a property with didSet stops the superclass's observers from running
- You can add didSet to an inherited let to log its value
- A read-write property can be overridden as read-only to lock it down
- Observers never run during any initializer, including a subclass's