Quantcast
Viewing all articles
Browse latest Browse all 12

Answer by Analog File for What is the purpose of willSet and didSet in Swift?

I do not know C#, but with a little guesswork I think I understand what

foo : int {    get { return getFoo(); }    set { setFoo(newValue); }}

does. It looks very similar to what you have in Swift, but it's not the same: in Swift you do not have the getFoo and setFoo. That is not a little difference: it means you do not have any underlying storage for your value.

Swift has stored and computed properties.

A computed property has get and may have set (if it's writable). But the code in the getter and setter, if they need to actually store some data, must do it in other properties. There is no backing storage.

A stored property, on the other hand, does have backing storage. But it does not have get and set. Instead it has willSet and didSet which you can use to observe variable changes and, eventually, trigger side effects and/or modify the stored value. You do not have willSet and didSet for computed properties, and you do not need them because for computed properties you can use the code in set to control changes.


Viewing all articles
Browse latest Browse all 12

Trending Articles