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 02 var celsius: Double = 0 { // Runs before the new value is stored3 willSet { // celsius is still the old value; newValue is the incoming one4 print("Changing from \(celsius) to \(newValue)")5 } // Runs after the new value is stored6 didSet { // celsius is now the new value; oldValue is the previous one7 print("Changed by \(celsius - oldValue) degrees")8 }9 }10}11 // Observers do not run during initialization12let temp = Temperature()// Prints Changing from 0.0 to 25.0 and Changed by 25.0 degrees13temp.celsius = 25.0// Prints Changing from 25.0 to 30.0 and Changed by 5.0 degrees14temp.celsius = 30.0Output
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=× 4\× 3-× 1:× 1