Property observers in Swift allow you to monitor and respond to changes in a property's value. They can be exceptionally useful for tasks where you need to execute some code whenever a property changes.
Swift provides two types of property observers: willSet
and didSet
. These observers are called automatically when the property is about to change (for willSet
) or just after it changes (for didSet
).
willSet
ObserverThe willSet
observer gets called right before the property value is updated. You can use willSet
to track the old value before it’s modified. The new value is passed as a parameter, often named newValue
by default.
class ObservableProperty {
var value: Int = 0 {
willSet(newVal) {
print("Value will change to \(newVal)")
}
}
}
In this example, every time the value
property is about to change, the current and incoming values are printed to the console.
didSet
ObserverThe didSet
observer gets called immediately after the property value changes. It is mainly used to perform actions in response to the new value of the property.
class ObservableProperty {
var value: Int = 0 {
didSet {
print("Value has changed to \(value)")
}
}
}
In this example, after the value
property is updated, the new value is printed to the console.
willSet
and didSet
You can use both observers together to monitor a property before and after its value changes, which can be helpful for debugging and tracking state changes.
class ObservableProperty {
var value: Int = 0 {
willSet {
print("Value will change from \(value) to \(newValue)")
}
didSet {
print("Value changed from \(oldValue) to \(value)")
}
}
}
Here, we observe both the upcoming change and the final new value, allowing us to see both states for comprehensive monitoring.
Property observers in Swift are a powerful feature to effectively monitor and react to property changes. Whether you need to validate data, trigger updates, or track state changes, willSet
and didSet
provide clean and concise ways to manage these tasks.