OC中,要实现懒加载是用到getter方法,例如
#pragma mark - Lazy Load
- (UIScrollView *)containerSV
{
if (!_containerSV)
{
_containerSV = [UIScrollView new];
[self.view addSubview:_containerSV];
[_containerSV mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
}];
}
return _containerSV;
}
Swift懒加载差别就很大了,懒加载属性用lazy修饰,注意结尾的小括号,懒加载实际上是一个闭包,和OC的区别还有他不用判断为否为空,Swift懒加载的执行顺序是如果这个变量没有值,才会执行闭包。
lazy var containerSV : UIScrollView = {
let sv = UIScrollView()
self.view.addSubview(sv)
sv.snp.makeConstraints({ (make) in
make.edges.equalTo(self.view)
})
return sv
}()