记录一下swift的懒加载
OC回顾懒加载
- (UIButton *)but{
if (!_but){
_but = [UIButton buttonWithType:UIButtonTypeCustom];
[_but setTitle:@"宝贝" forState:UIControlStateNormal];
}
return _but;
}
下面来看swift怎么创建懒加载用到关键字lazy
swift有两种加载方法
第一种方式
lazy var butt = UIButton()
第二种方式可以设置更多的属性
lazy var but:UIButton ={
let but =UIButton()
but.setTitle("按钮", for: .normal)
return but
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print(but)
}
总结:用到的时候再加载,多次用到只加载一次,swift里用lazy关键字创建懒加载
链接:https://www.jianshu.com/p/ad394463b7a2
网友评论