结构可以在 Swift 中具有惰性属性 [实例化] 吗?
Can a struct have lazy properties [instantiation] in Swift?
结构可以在 Swift 中具有惰性属性 [实例化] 吗?
我找不到任何说明是或否的文档。一切仅以类为例。
如果可以的话,哪里可以找到例子吗?
谢谢
斯坦
是的,结构可以有惰性 属性。考虑这个例子:
class Stuff {
var stuff: Int
init(value: Int) {
print("Stuff created with value \(value)")
stuff = value
}
}
struct HasLazy {
lazy var object = Stuff(value: 1)
var object2 = Stuff(value: 2)
}
func testIt() {
print("in testIt")
var haslazy = HasLazy()
print("done")
haslazy.object.stuff = 17
print("\(haslazy.object.stuff)")
print("final")
}
testIt()
输出:
in testIt
Stuff created with value 2
done
Stuff created with value 1
17
final
请注意,标记为 lazy
的 属性 在首次访问 属性 时打印 "done"
之后才会初始化。
查看实际效果 here,然后在不使用 lazy
关键字的情况下尝试。
结构可以在 Swift 中具有惰性属性 [实例化] 吗?
我找不到任何说明是或否的文档。一切仅以类为例。
如果可以的话,哪里可以找到例子吗?
谢谢
斯坦
是的,结构可以有惰性 属性。考虑这个例子:
class Stuff {
var stuff: Int
init(value: Int) {
print("Stuff created with value \(value)")
stuff = value
}
}
struct HasLazy {
lazy var object = Stuff(value: 1)
var object2 = Stuff(value: 2)
}
func testIt() {
print("in testIt")
var haslazy = HasLazy()
print("done")
haslazy.object.stuff = 17
print("\(haslazy.object.stuff)")
print("final")
}
testIt()
输出:
in testIt Stuff created with value 2 done Stuff created with value 1 17 final
请注意,标记为 lazy
的 属性 在首次访问 属性 时打印 "done"
之后才会初始化。
查看实际效果 here,然后在不使用 lazy
关键字的情况下尝试。