BUNDLE: Jumpstart your iOS development with the Swift Power Pack – now available! >>

< Previous: It's play time: index(of:) and joined()   Next: Wrap up >

Property observers: didSet

There's one last thing to cover before this project is done, and it's really small and really easy: property observers.

Right now we have a property called score that is set to 0 when the game is created and increments by one whenever an answer is found. But we don't do anything with that score, so our score label is never updated.

One solution to this problem is to use something like scoreLabel.text = "Score: \(score)" whenever the score value is changed, and that's perfectly fine to begin with. But what happens if you're changing the score from several places? You need to keep all the code synchronised, which is unpleasant.

Swift has a simple and classy solution called property observers, and it lets you execute code whenever a property has changed. To make them work, you need to declare your data type explicitly (in our case we need an Int), then use either didSet to execute code when a property has just been set, or willSet to execute code before a property has been set.

In our case, we want to add a property observer to our score property so that we update the score label whenever the score value was changed. So, change your score property to this:

var score: Int = 0 {
    didSet {
        scoreLabel.text = "Score: \(score)"

Note that when you use a property observer like this, you need to explicitly declare its type otherwise Swift will complain.

Using this method, any time score is changed by anyone, our score label will be updated. That's it, the project is done!

Upgrade to the premium experience

Get all 40 projects in PDF and ePub, plus exclusive content that will take your Swift learning to the next level – buy the Hacking with Swift book today!

< Previous: It's play time: index(of:) and joined()   Next: Wrap up >
Click here to visit the Hacking with Swift store >>