swift - 结构不调用新对象上的属性观察器

标签 swift struct computed-properties didset property-observer

在这段代码中,我想要 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/

相关文章:

ios - 将 View Controller View 添加到 subview 时发现 nil

c - 添加到链表时释放临时节点

单个 C 头文件中的循环依赖。需要前向声明吗?

vuejs2 - 如何使用 Vue.js 从单个文件组件中的方法访问计算属性

polymer - 手动重新计算 'computed properties'

ios - 对象函数后的 Swift 回调

ios - 当手机进入横向状态时,以编程方式更改自定义表格单元格中标签的约束。 ios 快速

Swift 计算属性模板?

ios - 没有 self 的自动释放池访问方法中的 Swift 闭包

c - typedef 一个结构到与该结构同名的点