首页 > 解决方案 > 结构不在新对象上调用属性观察者

问题描述

在这段代码中,我想在property observers创建新对象时调用。我如何实现这一目标?

这是我到目前为止所拥有的:

struct MyStruct {
    var myValue: Int {
        willSet {
            print("willSet")
        }
        didSet {
            print("didSet")
        }
    }
}

var abc = MyStruct(myValue: 3) // Does not use property observers
abc.myValue = 5 // Calls property observers

标签: swiftstructcomputed-propertiesdidsetproperty-observer

解决方案


您可以按如下方式构造自定义初始化程序。

struct MyStruct {
    var myValue: Int {
        willSet {
            print("willSet")
        }
        didSet {
            print("didSet")
        }
    }

    init(value: Int) {
        myValue = value
        // print something here
    }
}

var abc = MyStruct(value: 3) 
abc.myValue = 5 

推荐阅读