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 willSet and didSet 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?

11 Answers
11

Leave a Comment