【问题标题】:Multiple Getters for Swift Properties?Swift 属性的多个 Getter?
【发布时间】:2017-07-29 20:25:53
【问题描述】:

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

【问题讨论】:

    标签: swift getter-setter computed-properties


    【解决方案1】:

    使用Lazy Stored Property

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

    computeComputationallyIntensive 的调用(如果有)将在第一次调用computationallyIntensive 期间进行。

    【讨论】:

    • 有什么方法可以将 setter 添加到惰性 var 中?换句话说,惰性变量是否适用于计算属性?
    • @BrandonBradley 我的理解是惰性属性必须被计算,所以它们不允许设置器。
    猜你喜欢
    • 1970-01-01
    • 2015-05-15
    • 2011-01-08
    • 2017-12-23
    • 2014-07-29
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 2011-08-08
    相关资源
    最近更新 更多