クラス(その2)



クラスプロパティの監視


// クラスプロパティの監視
class User4 {
    let name: String
    var age: Int {
        willSet {
            print("\(age) -> \(newValue)")
        }
        didSet{
            print("\(oldValue - age)")
        }
    }
    init(_ name: String, _ age: Int){
        self.name = name
        self.age = age
    }
}
let user4 = User4("takai", 32)
user4.age = 10                  // 32 -> 10  22
user4.age = 32                  // 10 -> 32  -22    
            

継承


// クラスの継承
class User5 {
    let name: String
    var age: Int
    init(_ name: String, _ age: Int){
        self.name = name
        self.age = age
    }
    func printMessage(_ msg: String){
        print("\(msg) \(name)")
    }
}
let user5 = User5("morita", 32)
user5.printMessage("Hello")         //----- Hello morita

class AdminUser: User5{
    func printMessage(){
        print("Hi! \(name)")
    }
    override func printMessage(_ msg: String) {
        print("[Admin]\(msg) \(name)")
    }
}
let user6 = AdminUser("taka",40)
user6.printMessage()                //----- Hi! taka
user6.printMessage("Oh!")           //----- [Admin]Oh! taka