Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAkos Turi
7,517 Pointsbit confused
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
this is from the apple developer documentation. In this example willSet immediately prints the new value, what is the newTotalSteps and the old value is used in the didSet method. In the example what Pasan gave us, according to my interpretation, exactly the opposite happens, because the oldValue is printed out in the willSet method and the newValue is printed in the didSet.
1 Answer
Ramiro H Lopez
4,754 PointsI was a bit confused as well, but then I realized that the text string that is printing is what is causing the confusion. What is actually being printed out is the "value" variable itself, not the newValue and oldValue that is encapsulated by willSet and didSet.
Try changing the print statement in willSet to:
print("Changing from (value) to newValue: (newValue)")
and didSet to:
print("Changing from oldValue: (oldValue) to (value)")