Search code examples
swiftpropertiesobservers

How to use customisation provided in property observers?


I pasted this code from Swift programming language PDF Property Chapter and I want to know How can I use the customisation provided in willSet and didSet I mean in what situation this code uses println provided in willSet and didSet and prints "about to set steps tp(newTotalSteps)" or the other one ...?

class StepCounter {
    var totalSteps:Int=0
        {
            willSet(newTotalSteps){
                println("about to set total steps to\(newTotalSteps)")
            }
        didSet{
            if totalSteps>oldValue
            {
                println("Added\(totalSteps-oldValue)")
            }
        }
    }
}
let stepcounter=StepCounter()
stepcounter.totalSteps=200
stepcounter.totalSteps=360

Solution

  • Open a playground. Copy & Paste your code in. Then on right panel, click the + and you can see the console output, play it.

    enter image description here