有没有办法判断惰性变量是否已初始化?
Is there a way to tell if a lazy var has been initialized?
在我需要显示它的视图之前,我不想初始化视图控制器。所以我将它放在一个惰性变量中,例如:
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
是在 foo
被引用之前设置的,但每次我调用 if foo != nil
时,它都会初始化 foo
:c
有什么方法可以测试 foo
是否已设置 ?
lazy
只是对一种特定的惰性实例化模式(并且只是适度有用的模式)的便利包装。如果你想要自己的模式,不要使用 lazy;自己动手吧。
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
}
}
}
这是为了遵循 isViewLoaded
模式而设计的,它解决了相同的基本问题。
使用 Swift 内置惰性语义的较短版本:
struct Foo {
lazy var bar: Int = {
hasBar = true
return 123
}()
private(set) var hasBar = false
}
只需检查 hasBar
。
我在项目中使用的实际解决方案是使用 the Lazy Containers package that I created, in which I included an isInitialized
字段:
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
}
}
}
在我需要显示它的视图之前,我不想初始化视图控制器。所以我将它放在一个惰性变量中,例如:
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
是在 foo
被引用之前设置的,但每次我调用 if foo != nil
时,它都会初始化 foo
:c
有什么方法可以测试 foo
是否已设置 ?
lazy
只是对一种特定的惰性实例化模式(并且只是适度有用的模式)的便利包装。如果你想要自己的模式,不要使用 lazy;自己动手吧。
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
}
}
}
这是为了遵循 isViewLoaded
模式而设计的,它解决了相同的基本问题。
使用 Swift 内置惰性语义的较短版本:
struct Foo {
lazy var bar: Int = {
hasBar = true
return 123
}()
private(set) var hasBar = false
}
只需检查 hasBar
。
我在项目中使用的实际解决方案是使用 the Lazy Containers package that I created, in which I included an isInitialized
字段:
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
}
}
}