How do property observers (willSet/didSet) work?

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

Property Observers Swift willSet didSet Temperature Class Observing Changes