swift - 结构不在新对象上调用属性观察者
问题描述
在这段代码中,我想在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
推荐阅读
- javascript - 如何查询包含对象数组中给定键字段的文档?
- javascript - 反应钩子。单击时如何使其他项目(当前项目除外)停用
- swift - SwiftUI @Published 对象不会更新双结构数组的 UI
- flutter - Flutter:编程一个带有缩放的绘画应用(GestureDetector onScaleUpdate,缩放后的偏移量计算)
- matlab - Matlab polyfit 的根,带有 mu 用于居中和缩放
- mysql - 将phpmyadmin上的数据导入多个表
- rust - 从函数返回未来值
- javascript - JS - 带图像的单选按钮
- java - Spring Boot 应用无法使用 SSH 启动
- android - 在 AMD 处理器上运行 android 模拟器