Getting property changing notifications using property observers
You may often find that you would like to know when a property changes its value; maybe you want to update the value of another property, or inform a delegate. In Objective-C, this was often accomplished by writing your own getter and setter, or using Key-Value observing (KVO), but we have native support for property observers in Swift.
Getting ready
To examine property observers, we should create an object with a property that we want to observe. Let's create an object to manage users and a property to hold the current user's name:
class UserManager { var currentUserName: String = "Emmanuel Goldstein" }
We want to present some friendly messages when the current user changes, and we'll use property observers to do it.
How to do it...
Amend the currentUserName
property definition to be the following:
class UserManager { var currentUserName: String = "Emmanuel Goldstein" { willSet (newUserName) { print...