Search code examples
swiftlazy-initialization

Lazy initialization inside willSet issue


I'm trying to create optional array, but I want the initialization to be only before appending element into.

So I wrote:

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

But I get this error:

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


Solution

  • If you want a lazy bar then you should do it like...

    lazy var names: [String] = []