问题描述
在此文章,它说(请参考下面的代码):您必须使用惰性来防止多次创建闭包."
In this article, it says (referencing the code below): "You must use lazy to prevent the closure for being created more than once."
private lazy var variable:SomeClass = {
let fVariable = SomeClass()
fVariable.value = 10
return fVariable
}()
为什么懒惰会阻止多次创建闭包?为什么缺乏惰性会导致它多次评估呢?
Why would lazy prevent the closure from being created more than once? And why would the lack of lazy cause it to evaluate more than once?
推荐答案
您引用的教程代码是这样的:
The tutorial code you quote is this:
private lazy var variable:SomeClass = {
let fVariable = SomeClass()
fVariable.value = 10
return fVariable
}()
与此相反:
private var variable:SomeClass {
let fVariable = SomeClass()
fVariable.value = 10
return fVariable
}
第一个将variable
初始化为一个新创建的SomeClass实例,该实例最多一次 (也许没有那么多次).第二个是只读的计算变量,每次读取其值时都会创建一个新的SomeClass实例.
The first one initializes variable
to a newly created SomeClass instance, once at most (and maybe not even that many times). The second one is a read-only computed variable and creates a new SomeClass instance every time its value is read.
这篇关于带有关闭的惰性变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!