Property Observers

Property observers are a super-awesome feature built directly into Swift. They allow you to track and reply to changes of a property. You can add property observers to any property except lazy properties, which you won’t learn about here. Here’s how you create a basic property observer:

class Car {    var name:String = "Honda" {    willSet(newName) {        println("About to set the new name to \(newName)")    }    didSet(oldName) {        println("We just set 'name' to the new name \(name) from the old name           \(oldName)")    }    }}var car1:Car = Car()car1.name = "Ford"// About to set the new name to Ford// just set name to the new name Ford from the old name Honda

Notice that you add ...

Get Learning Swift™ Programming 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.