码迷,mamicode.com
首页 > 其他好文 > 详细

Lazy Stored Properties

时间:2018-06-05 21:16:24      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:until   函数   The   self   init   complex   first   ESS   require   

第一次使用的时候进行计算和初始化,后面的引用不在进行计算。

lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

NOTE

You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.

Lazy properties are useful when the initial value for a property is dependent on outside factors whose values are not known until after an instance’s initialization is complete. Lazy properties are also useful when the initial value for a property requires complex or computationally expensive setup that should not be performed unless or until it is needed.

 

class Lazytest{

    var xx = 1

    lazy var ee:String = {

        return "\(self.xx)"

    }()

    

    lazy var ff = {

        return "\(self.xx)"

    }

    

    lazy var gg = {para in

        return para + "\(self.xx)"

    }

}

 

有无括号的区别。无括号时为匿名函数

 

ee.storage   String? "1" some

ff.storage    (() -> String)? nil none

gg.storage   ((String) -> String)? nil none

 

(lldb) po px.ff()

"4"

(lldb) po px.gg("aa")

"aa4"

 

Lazy Stored Properties

标签:until   函数   The   self   init   complex   first   ESS   require   

原文地址:https://www.cnblogs.com/feng9exe/p/9141517.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!