What is the purpose of the 'didSet' and 'willSet' property observers in Swift?
Instruction: Provide an explanation and example of how 'didSet' and 'willSet' are used in Swift.
Updated
Official answer
willSet runs before an observed stored property changes and receives the proposed value. didSet runs afterward and receives the old value. They run when the property is assigned even if the value compares equal. They are synchronous hooks, not background jobs or validation that can throw from a setter.
This complete example initializes the property and records the ordering:
final class Settings {
var events: [String] = []
var theme: String = "system" {
willSet { events.append("will:\(theme)->\(newValue)") }
didSet { events.append("did:\(oldValue)->\(theme)") }
}
init(theme: String) { self.theme = theme }
}
let settings = Settings(theme: "light")
assert(settings.events.isEmpty)
settings.theme = "dark"
assert(settings.events == ["will:light->dark", "did:light->dark"])
settings.theme = "dark"
assert(settings.events.suffix(2) == ["will:dark->dark", "did:dark->dark"])
The direct assignment to this type's own stored property during initialization does not call these observers. Inherited property initialization has separate rules; do not generalize the example to every superclass/subclass path.
Use old/new comparisons to skip redundant downstream work when useful. If assigning to the same property from its didSet observer, Swift uses that new value without recursively invoking that observer again. Still avoid feedback cycles through other properties or observers. For rejectable input, use a validated method or explicit state transition instead of reporting success and repairing invalid state afterward.
Keep expensive processing out of these hooks, and honor UI actor isolation before updating views. A property observer does not make concurrent mutations safe.