willSet 问题中的延迟初始化

Lazy initialization inside willSet issue

我正在尝试创建可选数组,但我希望仅在将元素附加到其中之前进行初始化。

所以我写道:

    var names: [String]? {
        willSet {
            if names == nil {
                names = []
            }
        }
    }

但是我得到这个错误:

Attempting to store to property 'names' within its own willSet, which is about to be overwritten by the new value

如果你想要一个懒人吧,那么你应该这样做......

lazy var names: [String] = []