Swift可以懒惰和didSet设置在一起

Wil*_* Hu 15 swift

我有一个房产

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
    }()
Run Code Online (Sandbox Code Playgroud)

我想添加一个didSet方法,是否可能?

dfr*_*fri 20

简答:不.

在你的某些类或方法中尝试这个简单的例子:

lazy var myLazyVar: Int = {
    return 1
} () {
    willSet {
        print("About to set lazy var!")
    }
}
Run Code Online (Sandbox Code Playgroud)

这会给您以下编译时错误:

懒惰的属性可能没有观察者.


关于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
Run Code Online (Sandbox Code Playgroud)


Jos*_*ord 8

简短的回答是正如其他人所说的"不",但有一种方法可以使用内部隐藏的懒惰变量和计算变量来获得效果.

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
    }
}
Run Code Online (Sandbox Code Playgroud)