iOS: Swift——属性观察者

class Man {
    
    var name:String="lzh"
    
    var age:Int=0{//存储属性
        
        willSet{
            
            print("super new \(newValue)")
            
        }
        
        didSet{
            
            print("super new \(oldValue)")
            
        }
        
    }
    
    var height:Double{
        
        get{
            
            print("super get")
            
            return 10.0
            
        }
        
        set{
            
            print("super set")
            
        }
        
    }
    
}

class SuperMan:Man{
    
//    可以在子类中重写父类的存储属性为属性观察器
    
    override var name:String{
        
        willSet{
            
            print("newname \(newValue)")
            
        }
        
        didSet{
            
            print("oldname \(oldValue)")
            
        }
        
    }
    
//    可以在子类中重写父类的属性观察器
    
    override var age:Int{
        
        willSet{
            
            print("child newage \(newValue)")
            
        }
        
        didSet{
            
            print("child oldage \(oldValue)")
            
        }
        
    }
    
//    可以在子类重写父类的计算属性为属性观察器
    
    override var height:Double{
        
        willSet{
            
            print("child height \(newValue)")
            
        }
        
        didSet{
            
            print("child height \(oldValue)")
            
        }
        
    }
    
}

var m = SuperMan()
m.name = "Hugo"
m.age = 18
m.height = 180
  • 输出结果:

newname Hugo
oldname lzh
child newage 18
super new 18
super new 0
child oldage 0
super get
child height 180.0
super set
child height 10.0
Program ended with exit code: 0

你可能感兴趣的:(iOS: Swift——属性观察者)