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()
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()
Richard Venable
source share