Is there a way to tell if a lazy var has been initialized?
lazy
is just a convenience wrapper around one specific lazy-instantiation pattern (and one that is only moderately useful). If you want your own pattern, don't use lazy; just build it yourself.
private var _foo: NSViewController? = nil
var foo: NSViewController {
if let foo = _foo {
return foo
}
let foo = NSViewController()
foo.representedObject = self.representedObject
_foo = foo
return foo
}
// This can be private or public, as you like (or you don't technically need it)
var isFooLoaded: Bool {
return _foo != nil
}
override var representedObject: Any? {
didSet {
if !isFooLoaded {
foo.representedObject = representedObject
}
}
}
This is designed to follow the isViewLoaded
pattern, which addresses the same basic problem.
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.