Property Observer
Introduction
Welcome to Lesson 3 of Object Oriented Swift. You are going to learn how to add an observer to a property so that you may track when it is mutated or anything happens.
Problem
How can I add observer/tracker to a property?
willSet and didSet
willSetis called just before the value is setdidSetis called immediately after the new value is set to the property.
Grade Tracker
1. var myGrade: Int = 80 {
2. willSet(newGrade) {
3. print("About to change your grade to \(newGrade)")
4. }
5. didSet {
6. print("Your grade has been changed")
7. print("you had \(oldValue) previously. Now you have \(myGrade)")
8. }
9. }
Let us modify myGrade.
1. myGrade = 100
2. // "About to change your grade to 100"
3. // "Your grade has been changed"
4. // "You had 80 previously. Now you have 100"
The willSet block is called before myGrade is set to 100. The didSet block runs only after. oldValue refers to the initial value.
Step Counter
Create a variable called, totalSteps. When the variable encounters a new value, you may notify the user that the value has been changed.
1. var totalSteps: Int = 20 {
2. willSet(newTotalSteps) {
3. print("About to set totalSteps to \(newTotalSteps)")
4. }
5. didSet {
6. if totalSteps > oldValue {
7. print("Added \(totalSteps - oldValue) steps")
8. }
9. }
10. }
1. totalSteps = 60
2. // "About to set totalSteps to 60"
3. // "Added 20 steps"
Application
You may notify the user or change background color once the user successfully logs in to the app.
1. var userLoginInfo: Bool = false {
2. willSet(newValue) {
3. print("The user has tried something")
4. }
5. didSet {
6. if userLoginInfo {
7. print("The user has switched from \(oldValue) to \(userLoginInfo)")
8. // Backgroud color
9. // Animation
10. // Pop Up
11. // All kinds of stuff
12. }
13. }
14. }
16. userLoginInfo = true
17. // The user has tried something
18. // The user has switched from false to true
19. userLoginInfo = true
20. // The user has tried something
21. // The user has switched from true to true
Similarity with Computed Property
- Always recalculated even if the value has not changed.
What makes Property Observers different
- There is a default value and it is observed rather than calculated.
willSetanddidSetwill not get called when you initialize it.
Source Code
2003_property_observers.playground
Conclusion
The purpose of using property observers is not only to write less code but also to provide greater readability through the distinctive keywords. You no longer have to create unnecessary functions filled with switch or else-if statements. No need.
In the next lesson, you will design init methods that may return nil through failable initializations.
Note: Learn Swift with Bob is available on Udemy. If you wish to receive a discount link, you may sign up here.
