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 02 var celsius: Double = 0 { // Called just before the value changes3 willSet { // newValue is the value about to be stored4 print("Changing from \(celsius) to \(newValue)")5 } // Called just after the value changes6 didSet { // oldValue is the value before the change7 print("Changed by \(celsius - oldValue) degrees")8 }9 }10}11 // The initial value 0 does not trigger the observers12let temp = Temperature()// The literal 25 becomes the Double 25.0: Changing from 0.0 to 25.0, Changed by 25.0 degrees13temp.celsius = 25// Prints Changing from 25.0 to 30.0 and Changed by 5.0 degrees14temp.celsius = 30Output
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. 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