8

I have a class as property with a property observer. If I change something in that class, is there a way to trigger didSet as shown in the example:

class Foo {
    var items = [1,2,3,4,5]
    var number: Int = 0 {
        didSet {
            items += [number]
        }
    }
}

var test: Foo = Foo() {
    didSet {
        println("I want this to be printed after changing number in test")
    }
}

test.number = 1 // Nothing happens
Henny Lee
  • 2,970
  • 3
  • 20
  • 37

1 Answers1

11

Nothing happens because the observer is on test, which is a Foo instance. But you changed test.number, not test itself. Foo is a class, and a class is a reference type, so its instances are mutable in place.

If you want to see the log message, set test itself to a different value (e.g. a different Foo()).

Or, add the println statement to the other didSet, the one you've already got on Foo's number property.

Or, make Foo a struct instead of a class; changing a struct property does replace the struct, because a struct is a value type, not a reference type.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 2
    of course... sometimes I want to hit myself having tried to find an answer over hours while I should have just used a struct... thanks! – Henny Lee Apr 05 '15 at 03:47
  • 1
    You might want to look at my book, where I summarize the differences between the behaviors of value types vs. reference types: http://www.apeth.com/swiftBook/ch04.html#SECreferenceTypes Response of `didSet` on a struct reference to a change in a property of the struct is one of the first examples I give. – matt Apr 05 '15 at 04:35