Lazy Stored Properties

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

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"

猜你喜欢

转载自www.cnblogs.com/feng9exe/p/9141517.html