Property Observer in Swift

Level 4237 keystrokes

willSet runs just before celsius changes and receives newValue; didSet runs just after and receives oldValue. Each of the two assignments prints one line from each observer.

Swift code

1class Temperature {
// Stored property with observers, initially 0
2 var celsius: Double = 0 {
// Runs before the new value is stored
3 willSet {
// celsius is still the old value; newValue is the incoming one
4 print("Changing from \(celsius) to \(newValue)")
5 }
// Runs after the new value is stored
6 didSet {
// celsius is now the new value; oldValue is the previous one
7 print("Changed by \(celsius - oldValue) degrees")
8 }
9 }
10}
11
// Observers do not run during initialization
12let temp = Temperature()
// Prints Changing from 0.0 to 25.0 and Changed by 25.0 degrees
13temp.celsius = 25.0
// Prints Changing from 25.0 to 30.0 and Changed by 5.0 degrees
14temp.celsius = 30.0

Output

Changing from 0.0 to 25.0
Changed by 25.0 degrees
Changing from 25.0 to 30.0
Changed by 5.0 degrees
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • (× 6
  • )× 6
  • .× 4
  • "× 4
  • {× 4
  • }× 4
  • =× 4
  • \× 3
  • -× 1
  • :× 1

More Swift examples at level 4

← Swift typing practice