在Swift 3中有没有办法让一个具有计算属性的类第一次计算成本很高,但之后保持不变,要有单独的getter(初始的,然后是每个后续请求的另一个)?即。
class Example {
var computationallyIntensive: String? {
return try? String(contentsOf: unlistedFile, encoding: .utf8)
}
}
我知道初始化器,但是这个属性不需要在创建类时初始化。
理想情况下,第二次调用会比第一次调用更快地返回:
let test = Example()
if test.computationallyIntensive == "base case" {
print(test.computationallyIntensive)
}
答案 0 :(得分:2)
lazy var computationallyIntensive: String? = computeComputationallyIntensive()
func computeComputationallyIntensive() -> String? {
return try? String(contentsOf: unlistedFile, encoding: .utf8)
}
computeComputationallyIntensive
的来电(如果有的话)将在第一次致电computationallyIntensive
时发生。