Swift Property Observers
2 min readSep 2, 2024
Swift allows you to observe and respond to changes in a property’s value using willSet
and didSet
observers. These observers are called just before and immediately after the value is set.
Let’s Break It Down with a Different Example:
Imagine you have a class called TemperatureMonitor
that tracks the temperature of a device. The device needs to trigger an alarm if the temperature exceeds a certain threshold.
Here’s how you might implement this using property observers:
class TemperatureMonitor {
var temperature: Double = 20.0 { // Initial temperature is set to 20.0 degrees
willSet(newTemperature) {
print("Temperature is about to change from \(temperature) to \(newTemperature)")
}
didSet {
if temperature > 75.0 {
triggerAlarm()
}
print("Temperature changed from \(oldValue) to \(temperature)")
}
}
func triggerAlarm() {
print("Warning: Temperature exceeded safe limits! Triggering alarm...")
}
}
let monitor = TemperatureMonitor()
monitor.temperature = 80.0
Explanation:
Property Definition (temperature
):
- The
TemperatureMonitor
class has atemperature
property that stores the current temperature.
willSet
Observer:
willSet
is called right before thetemperature
property is updated.- It has access to the new value (via
newTemperature
) that is about to be set. - In this example,
willSet
simply prints a message indicating that the temperature is about to change.
didSet
Observer:
didSet
is called right after thetemperature
property has been updated.- It has access to the old value (via
oldValue
) that the property had before the change. - In this example,
didSet
checks if the new temperature exceeds a safe limit (75.0 degrees). If it does, it calls thetriggerAlarm()
method to handle the situation. - It also prints a message showing the old and new temperature values.
Key Points:
- Property Observers (
willSet
anddidSet
): These are useful for monitoring changes to properties and performing additional actions when changes occur. - Restrictions: You cannot add
willSet
ordidSet
observers to a property in an extension. They must be declared in the original property declaration. - Inheritance: You can override properties in subclasses to add or modify property observers, allowing you to customize behavior in derived classes.
Comparison with Key-Value Observing (KVO):
- Swift Property Observers are compile-time features and are used within the class or its subclass to react to changes internally.
- KVO (from Objective-C) is more dynamic, allowing external objects to observe changes to a property. This is not available in the same way in Swift for value types or purely Swift-based classes.