Stored Property Observer in Swift
Firstly, letâs take a look at the following Code Example:
var str = "Hello, playground" { //"Hello, playground" willSet { print("willSet \(str) : \(newValue)") // "willSet Hello, playground : Hello, Antonio.\n" str = "Hi" print("willSet \(str) : \(newValue)") //"willSet Hi : Hello, Antonio.\n" } didSet { print("didSet \(str) : \(oldValue)") //"didSet Hello, Antonio. : Hello, playground\n" str = "Hi" print("willSet \(str) : \(newValue)") // //"didSet Hi : Hello, playground\n" } } str = "Hello, Antonio."
In Swift,
Stored Property has two function to notify observer when it will be set(trying but before it is set, willSet) and it has been set(trying and already set it, didSet). So, every time trying to set the property, the willSet function will be called first, followed by didSet.
Here I did an interesting experiment: trying to modify the property while these two observing functions are called.
In the willSet function, assign it to a new String âHiâ does not do anything. It looks like a temporary assignment, and then assign it back very soon, because in the next calling function didSet, str is âHello, Antonioâ, rather than âHiâ, also the oldValue was not changed either.
While, in the didSet function, assign it to a new String âHiâ does actually assign the String âHiâ to this property, it changed the propertyâs value indeed, though the oldValue is still âHello, playgroundâ.
This is because the willSet function is called before the Stored Property has actually been set, while the âdidSetâ function is called after the Stored Property has already been set. So, in willSet function, assign a new String will not change the property value, since it will be assigned soon, while in didSet function, the property has been assigned, there is no other assignment here, so if itâs assigned by a new String value, this property value will be changed.
There is one thing deserve to note, assign new value to the property in the willSet and didSet function will not invoke recursively willSet nor didSet observing function.

















