Learn

Another built-in feature of properties we might find useful is property observers. If access control is a lockset for our properties, property observers are the security cameras. Specifically, property observers let us know when observed properties are about to be, or have been modified.

There are two methods we can use to observe a stored property: willSet and didSet. As you might surmise, willSet is called right before we set the property, and didSet is called right afterward.

In the scope of willSet, we are given the new value that the property will be set to, with the default parameter name newValue. Alternatively we can define a custom name for the new value. Similarly, didSet gives you the old value that was previously assigned to the property, with the default name oldValue. Again, this can be overridden with a custom name.

Let’s explore the syntax of property observers in our cat example:

struct Cat { private var numberOfLives : Int { willSet { print("Uh-oh, number of lives is changing to \(newValue)") } didSet(oldLives) { print("Welp, we don’t have \(oldLives) anymore") } } init(numberOfLives: Int){ self.numberOfLives = numberOfLives } mutating func loseOneLife() { self.numberOfLives -= 1 } } var scrambles = Cat(numberOfLives: 9) scrambles.loseOneLife() //prints to console Uh-oh, number of lives is changing to 8 Welp, we don’t have 9 anymore

Note that we could have used a custom value for willSet as well, or we could have used the default value of oldValue in didSet.

Instructions

1.

Add a willSet property observer to the paperclipSales property that prints We adjusted the sales to {newValue} paperclips. to the console.

2.

Below the willSet property observer, add a didSet property observer to the paperclipSales property that prints Originally, we sold {oldValue} paperclips. to the console.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?