Swift属性的多个Getters?

时间:2017-03-09 02:10:38

标签: swift getter-setter computed-properties

在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)
}

1 个答案:

答案 0 :(得分:2)

使用Lazy Stored Property

lazy var computationallyIntensive: String? = computeComputationallyIntensive()

func computeComputationallyIntensive() -> String?  {
    return try? String(contentsOf: unlistedFile, encoding: .utf8)
}

computeComputationallyIntensive的来电(如果有的话)将在第一次致电computationallyIntensive时发生。