我有一个房产
public lazy var points: [(CGFloat,CGFloat,CGFloat)] = { var pointsT = [(CGFloat,CGFloat,CGFloat)]() let height = 100.0 for _ in 1...10 { pointsT.append((someValue,someValue,100.0)) } return pointsT }()
我想添加一个didSet
方法,是否可能?
简答:不.
在你的某些类或方法中尝试这个简单的例子:
lazy var myLazyVar: Int = { return 1 } () { willSet { print("About to set lazy var!") } }
这会给您以下编译时错误:
懒惰的属性可能没有观察者.
关于let
另一个答案中的陈述:懒惰变量不仅仅是"让具有延迟初始化的常量".请考虑以下示例:
struct MyStruct { var myInt = 1 mutating func increaseMyInt() { myInt += 1 } lazy var myLazyVar: Int = { return self.myInt } () } var a = MyStruct() print(a.myLazyVar) // 1 a.increaseMyInt() print(a.myLazyVar) // 1: "initialiser" only called once, OK a.myLazyVar += 1 print(a.myLazyVar) // 2: however we can still mutate the value // directly if we so wishes
简短的回答是正如其他人所说的"不",但有一种方法可以使用内部隐藏的懒惰变量和计算变量来获得效果.
private lazy var _username: String? { return loadUsername() } var username: String? { set { // Do willSet stuff in here if newValue != _username { saveUsername(newValue) } // Don't forget to set the internal variable _username = newValue // Do didSet stuff here // ... } get { return _username } }