zneak zneak - 7 months ago 31
Swift Question

What is the purpose of willSet and didSet in Swift?

Swift has a property declaration syntax very similar to C#'s:

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

However, it also has
actions. These are called before and after the setter is called, respectively. What is their purpose, considering that you could just have the same code inside the setter?


The point of the willSet and didSet keywords seem to be that it is possible to create a property with automatic storage that will still do something before or after it is set. For instance, in the following class:

class Foo
    var propertyChangedListener : (Int, Int) -> Void = {
        println("The value of myProperty has changed from \($0) to \($1)")

    var myProperty : Int = 0 {
        didSet { propertyChangedListener(oldValue, self.myProperty) }

myProperty has automatic storage, can be read from and written to, and yet it can still call propertyChangedListener without having an explicit backing store. This would not be possible with only get and set keywords.