2

为什么这段代码会在初始化时触发 didSet

final public class TestDidSet {

static var _shared: TestDidSet! = TestDidSet()

func testA() { }

private var test = true {
    didSet {
        print("didSet test when initing!!!!!:\(test)")
    }
}
private var _value: Bool! {
    didSet {
        print("didSet when initing!!!!!:\(_value)")
    }
}

private init() {
    testSet()
    _value = false
    test = false
}

private func testSet() {
    _value = true
}
}

TestDidSet._shared.testA()

任何想法?它不应该触发 didSet 吗?有人帮忙!

更新:我的观点是这样, testSet()并且_value = false正在做同样的事情,但是testSet()在外面init(),所以testSet()会触发didSet_value = false不是。为什么?!

我想,这不是导致“didSet”的可选类型或其他原因。

4

2 回答 2

1

当您声明具有隐式展开的可选类型(Bool!在您的情况下)的属性时,它会被隐式分配一个默认值nil. 然后,如果您在初始化程序中为其分配其他值,则didSet观察者会被触发,因为它已经是第二次分配。 didSet不应该只在第一个触发。

于 2016-05-25T10:55:26.730 回答
-3

每次您为属性分配新值时都会调用didSet{}闭包(即使您在声明(内联)或初始化时分配它)。

于 2016-05-25T12:02:43.080 回答