iOS:Swift-プロパティオブザーバー

1818 ワード

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