Mtoklitz113
Mtoklitz113

Reputation: 3878

Property observers and their behaviour

I've a sample class and a property of type Int like so:

class StepCounter {
    var totalSteps: Int = 0 {
        willSet(newTotalSteps) {
            print("about to set steps to \(newTotalSteps)")
        }
        didSet {
            if totalSteps > oldValue {
                print("Added \(totalSteps - oldValue) steps")
            }

        }
    }
}

Now when I make an instance of this class and assign a number to my var totalSteps like so:

let anObj = StepCounter()

anObj.totalSteps = 2000

I get the console output as expected:

about to set steps to 2000
Added 2000 seteps

But when I do anObj.totalSteps -= 1, I get only the willSet output saying about to set steps to 1999 and the didSet never gets executed. What is happening and why I'm not getting the willSet print statement executed? Do help, thanks.

Upvotes: 1

Views: 51

Answers (1)

Eric Aya
Eric Aya

Reputation: 70097

In your didSet you have:

if totalSteps > oldValue

But when you do anObj.totalSteps -= 1, the total steps are not greater than the old value!

So the print is not executed, as expected. :)

Upvotes: 1

Related Questions