Property Observer in Swift

Level 4233 keystrokes

willSet and didSet run around every assignment to celsius: willSet sees the incoming newValue, didSet sees the previous oldValue. Two assignments produce four lines of output.

Swift code

1class Temperature {
// Observed stored property, starting at 0
2 var celsius: Double = 0 {
// Called just before the value changes
3 willSet {
// newValue is the value about to be stored
4 print("Changing from \(celsius) to \(newValue)")
5 }
// Called just after the value changes
6 didSet {
// oldValue is the value before the change
7 print("Changed by \(celsius - oldValue) degrees")
8 }
9 }
10}
11
// The initial value 0 does not trigger the observers
12let temp = Temperature()
// The literal 25 becomes the Double 25.0: Changing from 0.0 to 25.0, Changed by 25.0 degrees
13temp.celsius = 25
// Prints Changing from 25.0 to 30.0 and Changed by 5.0 degrees
14temp.celsius = 30

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
  • \× 3
  • .× 2
  • -× 1
  • :× 1

More Swift examples at level 4

← Swift typing practice