December 2018
Intermediate to advanced
414 pages
10h 19m
English
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 ...
Read now
Unlock full access