The last observation technique that we can use is baked right into the Swift language. Unlike the previous techniques, this doesn't let you register multiple observers, only one—the current object. While this is a bit of an aside to the observer pattern, this technique still falls into this category.
Swift exposes willSet and didSet, which you can use on the properties themselves:
struct Article {
var title: String = "" {
willSet {
// here the title is the value before setting
if title != newValue {
print("The title will change to \(newValue)")
}
}
didSet {
// here the title is the value after it's been set
if title != oldValue {
print("The title has changed from \(oldValue)")
}
}
}
}
In the preceding code, we print a line each time the title changes from the previous value. It prints the new value as well as the old value, after the new title is set:
var article = Article()
article.title = "A Good Title"
article.title = "A Good Title"
article.title = "A Better Title"
The output is as follows:
The title will change to A Good Title
The title has changed from
The title will change to A Better Title
The title has changed from A Good Title
Notice that the second setter doesn't print the following, as we are checking if the values are changing:
The title will change to A Good Title
The title has changed from A Good Title
This technique is useful if the scope of the observation is constrained to the object itself, for example, if you want to know if your local model has changed. This is particularly useful if, for example, your view has its model set from the outside, and you want to know when the model property is updated in order to render and update the different components that comprise your view.