Swift Property Observers (willSet / didSet)
In this article, we will explain property observers in Swift.
Basics of Property Observers in Swift
By using property observers in Swift, you can specify code that executes every time the value of a property is set.
There are two types of property observers: willSet and didSet.
willSet is called right before the property value changes.
didSet is called immediately after the property value changes.
The basic syntax of willSet and didSet is as follows:
var [propertyName]: [DataType] = [DefaultValue] {
willSet {
[statements executed right before the value changes]
}
didSet {
[statements executed immediately after the value changes]
}
}
Inside willSet, you can access the value that is about to be set using newValue.
You can also specify a custom parameter name, like willSet(customName), and then access it by that name.
Inside didSet, you can access the previous value of the property using oldValue.
Similarly, you can specify a custom parameter name, like didSet(customName), and access it by that name.
Note that property observers are executed even when the same value is assigned to the property again.
Using willSet and didSet in Swift
Now let's use property observers in Swift to execute code when a property value is set.
We'll define a class called TestClass like this:
class TestClass {
var count: Int = 0 {
willSet {
print("count will become \(newValue).")
}
didSet {
print("Previous: \(oldValue) -> Current: \(self.count)")
if oldValue == self.count {
print("count did not change.")
} else if oldValue < self.count {
print("count increased by \(self.count - oldValue).")
} else {
print("count decreased by \(oldValue - self.count).")
}
}
}
}
Here, we define an integer property count with an initial value of 0.
In willSet, before count changes, it prints “count will become \(newValue).”.
In didSet, after count changes, it prints both the old and new values and indicates how count changed.
Now let's create an instance of TestClass, assign values to count, and check the printed output:
let testClass = TestClass()
testClass.count = 5
print("-----")
testClass.count = 20
print("-----")
testClass.count = 20
print("-----")
testClass.count = 8
The output will be:
count will become 5.
Previous: 0 -> Current: 5
count increased by 5.
-----
count will become 20.
Previous: 5 -> Current: 20
count increased by 15.
-----
count will become 20.
Previous: 20 -> Current: 20
count did not change.
-----
count will become 8.
Previous: 20 -> Current: 8
count decreased by 12.
As you can see, every time the count property is assigned a value, both willSet and didSet are called.
They are executed even when the new value is the same as the old one.
That wraps up our explanation of property observers in Swift.