Swift中懒加载

前端之家收集整理的这篇文章主要介绍了Swift中懒加载前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

关键字是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 =  {
    @H_403_68@() -> Int in
    var a = 100
    var b = 100
    return a+b
}()

猜你在找的Swift相关文章