更改类中的属性时,有没有办法使didSet起作用?

更改类中的属性时,有没有办法使didSet起作用?

问题描述:

我有一个带有属性观察器的类作为属性.如果我在该类中进行了某些更改,是否有一种方法可以触发didSet,如示例所示:

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

什么都没有发生,因为观察者在作为Foo实例的test上.但是您更改了test.number而不是test本身. Foo是一个类,而class是一个引用类型,因此它的实例是可变的.

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.

如果要查看日志消息,请将test 本身设置为其他值(例如,其他Foo()).

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

或者,将println语句添加到 other didSet,这是您已经在Foo的number属性中获得的语​​句.

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

或者,使Foo成为一个结构而不是一个类;更改结构属性不会替换该结构,因为结构是值类型,而不是引用类型.

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.