'Is there a way to tell if a lazy var has been initialized?

I don't want to initialize a view controller until I need to display its view., so I have it in a lazy var like:

lazy var foo: NSViewController! = {
    let foo = NSViewController()
    foo.representedObject = self.representedObject
    return foo
}()

// ...

override var representedObject: Any? {
    didSet {
        if foo != nil {
            foo.representedObject = representedObject
        }
    }
}

self.representedObject is set before foo is ever referenced, but every time I call if foo != nil, it initializes foo :c

Is there any way I can test if foo has already been set?



Solution 1:[1]

A shorter version that uses Swift's built-in lazy semantics:

struct Foo {
    lazy var bar: Int = {
        hasBar = true
        return 123
    }()
    private(set) var hasBar = false
}

Just check for hasBar instead.

Solution 2:[2]

The actual solution I've gone with in my projects is to use the Lazy Containers package that I created, in which I included an isInitialized field:

import LazyContainers



@Lazy
var foo: NSViewController = {
    let foo = NSViewController()
    foo.representedObject = self.representedObject
    return foo
}()

// ...

override var representedObject: Any? {
    didSet {
        if _foo.isInitialized {
            foo.representedObject = representedObject
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel
Solution 2