Swift Property Observers

abdul ahad
2 min readSep 2, 2024

--

Photo by Joey Nicotra on Unsplash

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 a temperature property that stores the current temperature.

willSet Observer:

  • willSet is called right before the temperature 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 the temperature 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 the triggerAlarm() method to handle the situation.
  • It also prints a message showing the old and new temperature values.

Key Points:

  • Property Observers (willSet and didSet): These are useful for monitoring changes to properties and performing additional actions when changes occur.
  • Restrictions: You cannot add willSet or didSet 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.

--

--

abdul ahad
abdul ahad

Written by abdul ahad

A software developer dreaming to reach the top and also passionate about sports and language learning

No responses yet