Swift中懶載入

大招至勝發表於2017-09-07

關鍵字是lazy, 只能是var的變數才能懶載入

lazy var count = 100

lazy var count = {
    return 100
}()

//閉包中如果是多行程式碼就要報錯:unable to infer complex closure return type

lazy var count = {
    var a = 100
    var b = 100
    return a+b
}()

解決閉包不能推斷返回型別即可,下面三種方法

lazy var count: Int = {
    var a = 100
    var b = 100
    return a+b
}()

lazy var count = {
    var a = 100
    var b = 100
    return a+b
}() as Int

lazy var count =  {
    () -> Int in
    var a = 100
    var b = 100
    return a+b
}()

相關文章