Property Observers

suggest change

Property observers respond to changes to a property’s value.

var myProperty = 5 {
    willSet {
        print("Will set to \(newValue). It was previously \(myProperty)")
    }
    didSet {
        print("Did set to \(myProperty). It was previously \(oldValue)")
    }
}
myProperty = 6
// prints: Will set to 6, It was previously 5
// prints: Did set to 6. It was previously 5
Note: didSet and willSet will not be called in the following cases:
var myFontSize = 10 {
    willSet(newFontSize) {
        print("Will set font to \(newFontSize), it was \(myFontSize)")
    }
    didSet(oldFontSize) {
        print("Did set font to \(myFontSize), it was \(oldFontSize)")
    }
}
Caution: While it is supported to declare setter parameter names, one should be cautious not to mix names up:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents