In Swift, property observers allow you to observe and respond to changes in a property's value. The two main observers are willSet
and didSet
. The willSet
observer is called just before the value is set, while the didSet
observer is called immediately after the new value is stored.
These observers are particularly useful for tracking changes in settings, notifying other parts of your app, or performing any kind of side effect when a property's value changes.
Here is an example of how you can use property observers in a Swift class:
class Temperature {
var celsius: Double {
willSet {
print("About to set celsius to \(newValue)")
}
didSet {
print("celsius was set to \(celsius)")
fahrenheit = celsius * 9.0 / 5.0 + 32.0
}
}
var fahrenheit: Double = 0.0
init(celsius: Double) {
self.celsius = celsius
self.fahrenheit = celsius * 9.0 / 5.0 + 32.0
}
}
let temp = Temperature(celsius: 20)
temp.celsius = 25 // This will trigger the property observers
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?