Swift开发

Swift 懒加载

2017-11-27  本文已影响0人  追逐_chase
Swift.png
懒加载
//懒加载

class Person {
    
    lazy var name:String = "CC";
    
    lazy var dog:Dog = {
        
        let d = Dog();
        
        d.name = "哈哈";
        
        return d;
        
    }()
    
    
}

class Dog {
    
    lazy var name:String = "cc的小狗";
    
    
}

p.dog.name;   //  "哈哈"
Dog().name;  //  "cc的小狗"



//懒加载

class Person {
    
    lazy var name:String = "CC";
    
  //dog是可选类型
    lazy var dog:Dog? = {
        
        let d = Dog();
        
        d.name = "哈哈";
        
        return d;
        
    }()
    
    
}

class Dog {
    
    lazy var name:String = "cc的小狗";
    
    
}


let p = Person();

p.dog?.name;
Dog().name;

//dig值为nil
p.dog = nil;

p.dog?.name;  //打印结果是:nil



上一篇下一篇

猜你喜欢

热点阅读