Swift - Using Class Property Observers

Introduction

Swift lets you add observers to your properties.

These are code that can run just before or after a property's value changes.

To create a property observer, add braces after your property and include willSet and didSet blocks.

These blocks each get passed a parameter.

willSet is called before the property's value changes, and is given the value that is about to be set.

didSet is given the old value:

Demo

class MyClass { 
    var number  : Int = 0 { 
        willSet(newNumber) { /*from www.j  av  a  2s  .c  o  m*/
            print("About to change to \(newNumber)") 
        } 
        didSet(oldNumber) { 
            print("Just changed from \(oldNumber) to \(self.number)!") 
        } 
    } 
} 

var observer = MyClass() 
observer.number = 4

Result

Property observers don't change anything about how you actually work with the property.

They just add further behavior before and after the property changes.

Related Topic