Swift基础篇——懒加载

懒加载

import UIKit

class ViewController: UIViewController {
    // 只有外界访问到listData的时候才会去执行闭包, 然后将闭包的返回值赋值给listData
    // 注意: 一定要记住闭包后面需要写上(), 代表执行闭包
    lazy var listData: [String]? = {
        ()->[String]
        in
        print("----")
        return ["longshao", "guangzhou", "beijing", "shenzhen"]
        }()

    // 开发中这样写
    lazy var listData2: [String]? = {
        print("----")
        return ["longshao", "guangzhou", "beijing", "shenzhen"]
    }()

    lazy var listData3: [String]? = self.test()
    func test() -> [String]
    {
        print("+++")
        return ["lnj1", "lmj1", "why1", "wsz1"]
    }

    override func touchesBegan(touches: Set, withEvent event: UIEvent?) {
        print(listData!)
        print(listData)
        print(listData)

        print("++++++++++++++++++++++++++++")

        print(listData2)
        print(listData2)
        print(listData2)

        print("++++++++++++++++++++++++++++")

        print(listData3)
        print(listData3)
        print(listData3)
    }
}

你可能感兴趣的:(iOS那些事)