Swift中懒加载

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

关键字是lazy,只能是var的变量才能懒加载

@H_404_3@lazy @H_404_3@var count = 100

@H_404_3@lazy @H_404_3@var count = {
    @H_404_3@return 100
}()

//闭包中如果是多行代码就要报错:unable to infer complex closure return type

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

解决闭包不能推断返回类型即可,下面三种方法

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

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

lazy var count =  {
    () -> Int @H_404_3@in
    var a = 100
    var b = 100
    @H_404_3@return a+b
}()
原文链接:https://www.f2er.com/swift/321201.html

猜你在找的Swift相关文章