Does it set the same value for a property that still calls setSet and didSet?

If I set the property value to the same value that is currently set, will SET and didSet be called? It is important to know when you have side effects that occur in these functions.

+7
swift
source share
2 answers

Yes, willSet and didSet get called even when setting the same value. I tested it on the playground:

class Class1 { var willSetCount = 0 var didSetCount = 0 var var1: String = "A" { willSet { willSetCount++ } didSet { didSetCount++ } } } let aClass1 = Class1() // {0 0 "A"} aClass1.var1 = "A" // {1 1 "A"} aClass1.var1 = "A" // {2 2 "A"} 

If you want to prevent side effects from setting the same value, you can compare the value with newValue / oldValue:

 class Class2 { var willSetCount = 0 var didSetCount = 0 var var1: String = "A" { willSet { if newValue != var1 { willSetCount++ } } didSet { if oldValue != var1 { didSetCount++ } } } } let aClass2 = Class2() // {0 0 "A"} aClass2.var1 = "A" // {0 0 "A"} aClass2.var1 = "B" // {1 1 "B"} 
+12
source share

Yes Yes. You may have a type property that does not comply with the Equatable protocol, and then “the same value” does not make sense. willSet and didSet not called only when the value is set inside the initializer.

+7
source share

All Articles