在这段代码中,我想要 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
最佳答案
您可以按如下方式构造自定义初始值设定项。
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
关于swift - 结构不调用新对象上的属性观察器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50656861/