Swift Programming Tutorial: Property Observers using didSet and willSet
How to run a code before or after a value changes
--
For the sake of convenience, property observers are built so that developers doesn’t need to write a code repeatedly each time a value of a property (or a variable) changes. There are basically 2 kinds of property observers:
- willSet — executes a code right before the property changes.
- didSet — executes a code right after the property changes.
To understand it better, below is a simple example of a combined willSet and didSet code:
import Foundation
var user: String = "Batman" {
willSet { print("User will change") }
didSet { print("User was changed") }
}
user = "Robin"
The output will be:
User will change
User was changed
Explaining what happened to above code. When the value of user is changed to Robin, the property observers automatically executed its block of code. The willSet was executed first before it changes to Robin. Then once the value is changed to Robin, the didSet is executed.
Without property observers, you have to do it like this:
import Foundation
var user: String = "Batman"
func changeName(name: String) {
print("User will change")
user = name
print("User was changed")
}
changeName(name: "Robin")
The output is the same:
User will change
User was changed
Let’s assume that each time you update the value of user, the indicated print statements should also be executed as well. Using property observers makes handling this kind of tasks more convenient compared to traditional way of coding it. Like our case above, there’s no need to use the block of code (even if it is a function) repeatedly.
As an important note for novice programmers, you can just use the property observer that you need. Below is an example of a code where you’re just using didSet:
import Foundation
var user: String = "Batman" {
didSet {
print("User was changed")
}
}
user = "Robin"