Friday, February 12, 2016

Stored Property Observer in Swift

Firstly, let's take a look at the following Code Example:

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.

No comments :

Post a Comment