Quantcast
Channel: What is the purpose of willSet and didSet in Swift? - Stack Overflow
Viewing all articles
Browse latest Browse all 12

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

$
0
0

The point seems to be that sometimes, you need a property that has automatic storage and some behavior, for instance to notify other objects that the property just changed. When all you have is get/set, you need another field to hold the value. With willSet and didSet, you can take action when the value is modified without needing another field. For instance, in that example:

class Foo {    var myProperty: Int = 0 {        didSet {            print("The value of myProperty changed from \(oldValue) to \(myProperty)")        }    }}

myProperty prints its old and new value every time it is modified. With just getters and setters, I would need this instead:

class Foo {    var myPropertyValue: Int = 0    var myProperty: Int {        get { return myPropertyValue }        set {            print("The value of myProperty changed from \(myPropertyValue) to \(newValue)")            myPropertyValue = newValue        }    }}

So willSet and didSet represent an economy of a couple of lines, and less noise in the field list.


Viewing all articles
Browse latest Browse all 12

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>