Richard Venable
Richard Venable

Reputation: 8715

Does setting the same value for a property still call willSet and didSet?

If I set a property value to the same value as it is currently set to, will willSet and didSet get called? This is important to know when you have side effects occurring in these functions.

Upvotes: 18

Views: 5646

Answers (2)

Marián Černý
Marián Černý

Reputation: 15778

Yes, it does. You could have a property of type that does not conform to Equatable protocol and then "same value" would not make sense. willSet and didSet isn't called only when the value is set inside initializer (before the instance is fully initialized).

Upvotes: 11

Richard Venable
Richard Venable

Reputation: 8715

Yes, willSet and didSet get called even when setting to the same value. I tested it in a 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 happening when the same value is being set, you can compare the value to 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"}

Upvotes: 22

Related Questions