One of the powerful features in Swift is property observers. They allow you to observe and respond to changes in property values. Property observers can be added to stored properties, providing a convenient way to perform additional actions whenever the value of a property is set or changed.
In Swift, property observers are available for both stored properties and properties backed by observers. There are two types of property observers:
newValue
.oldValue
.A common use case for property observers is to validate or modify property values as they are being set. Let's consider an example to better understand property observers:
class Temperature {
var celsius: Double = 0.0 {
// willSet observer
willSet {
print("Updating temperature from \(celsius)°C to \(newValue)°C")
}
// didSet observer
didSet {
print("Temperature updated!")
}
}
}
let currentTemperature = Temperature()
currentTemperature.celsius = 25
In the above example, we define a class called Temperature
with a celsius
property. The property has both the willSet
and didSet
observers. Whenever the celsius
property is set or changed, these observers are triggered.
When we create an instance of Temperature
and set the celsius
property to 25, the observers are executed. The output will be:
Updating temperature from 0.0°C to 25.0°C
Temperature updated!
The willSet
observer prints a message showing the old value and the new value being set, while the didSet
observer simply prints a message stating that the temperature has been updated.
Using property observers, you can perform various actions whenever a property value changes, such as updating UI elements, logging, triggering other methods, or performing calculations.
Summary: Property observers in Swift allow you to observe and respond to changes in property values. They provide willSet
and didSet
observers, which are triggered just before and just after the value of a property is set or changed, respectively.