2020-11-17 懒加载 lazy

//懒加载,lazy语句会在init后执行
class SleepingBeauty {
    
    init(){
        print("zzz... 沉睡中。。。")
        //sleep(2)
        print("睡美人准备好了")
    }
}

class Castle {
    lazy var princess = SleepingBeauty()
    
    init() {
        print("城堡准备好了!")
    }
}

print("一座城堡即将出现。。。")
let castle = Castle()
castle.princess

用懒加载来避免可选型

class ViewController: UIviewController {
    lazy var label: UILabel = UILabel(frame: .zero)
    
    override func loadView(){
        super.loadView
        
        self.view.addSubview(self.label)
    }
    
    override func ViewDidLoad() {
        syper.viewDidLoad()
        
        self.label.textColor = .black
        self.label.font = UIFont.systemFont(ofSize: 16, weight: .bold)
    }
}

你可能感兴趣的:(2020-11-17 懒加载 lazy)