Property Observers
For regular stored properties, Swift will completely synthesize the code needed to set the value. What if you need the type to respond in some way to the setting? You write a "property observer". It’s added just like one of the
get
or
set
blocks we talked about with computed properties, but doesn’t interfere with the new value.
The most common one to write is a
didSet
, this lets your object respond in some way to the new state of the type. Suppose I have a controller object which needs to update the UI when a data model changes.
class UIElement {
func doSomething(text:String) {
print("element did something with \(text)")
}
}
class Controller {
var interfaceElement:UIElement?
var model:String = "" {
didSet {
interfaceElement?.doSomething(text:model)
}
}
}
let controller:Controller = Controller()
controller.interfaceElement = UIElement()
controller.model = "warning message"
//element did something with warning message
Swift property observers let you control an object’s behavior in response to its properties without interfering with the standard mechanisms for creating storage for that property.
willSet
is a companion to
didSet
which lets you access the old value before the new one comes in. The secret to
willSet
is that there’s an unlisted argument named
newValue
which contains the next value for the property.
var model:String = "" {
didSet {
interfaceElement?.doSomething(text:model)
}
willSet {
print("did have \(model), will be \(newValue)")
}
}
Comments for Property Observers