swift-懒加载的写法
- 懒加载的格式如下:
-
lazy var demoView: UIView = { let v = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) v.backgroundColor = UIColor.redColor() return v }()
- 懒加载本质上是一个闭包
- 以上代码可以改写为以下格式
let demoLazy = { () -> UIView in let v = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) v.backgroundColor = UIColor.redColor() return v } lazy var demoView: UIView = self.demoLazy()
- 懒加载的简单写法
lazy var dataList = [String]()