I read through this SO didSet q&a and Apple’s Property Observers and a few other posts. What I can’t seem to wrap my head around is what is the benefit of using didSet when mutating a variable when if you change the variable without using a property observer it’s going to change anyway?
Scenario 1:
var someVal = 0
someVal = 10
// someVal now holds 10
Scenario 2:
var someVal: Int = 0{
didSet{
}
}
someVal = 10
// again someVal now holds 10
Scenario 3:
var someVal: Int = 0{
didSet{
if someVal > oldValue{
someVal = newValue
}
}
}
someVal = 10
// once again someVal holds a value of 10
The only thing I see in Scenario 3 is that if the condition isn’t met then someVal won’t change. But instead of adding it inside the didSet I can simply do this and the same exact thing will occur.
var someVal = 0
var anotherVal = 10
if someVal < anotherValue{
someVal = anotherValue
}
// once again someVal holds a value of 10
So other then adding a condition inside a didSet observer what is the benefit?
Well, it's an observer. Many times you want to react to changing a value of a viewController property. Now if you modify that property on 10 different places, you don't have to copy/paste the same code 10 different times - the didSet
observer will take care of that.
E.g.:
var someVal: Int = 0 {
didSet {
somePostprocessing()
}
}
someVal = 10
// a bit later
someVal = 15
// etc.
is much better than:
var someVal: Int = 0
someVal = 10
somePostprocessing()
// a bit later
someVal = 15
somePostprocessing()
// etc.
In first case you can be sure that anytime the value changes, the postProcessing will happen. In the second case, even if we would be willing to accept copy/pasting (which is not OK), how can you be sure that you won't forget to add postProcessing in every case you modify the value?