Chapter    35

Property Observers

You can observe the state of a property with the willSet and didSet keywords. You can use these in the property declaration to assign an action that will occur when a property is about to change and when a property value just changed. Listing 35-1 shows how you would add an action that prints a message to the console log whenever the age property value is about to change and after the age value has changed.

Listing 35-1. Property Observers

class Person {    var name: String = "Name"    var age:Int = 0{    willSet{        println("age value is about to change to \(newValue)")    }    didSet{        println("age value just changed to \(self.age)")    }    }    func profile() -> String {        return "I'm \(self.name) ...

Get Swift Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.