クラス(その4)



プロトコル


protocol Drink {
    var type: String { get }      //読み込み専用
    var count: Int { get set }    //読み書きOK
    func Sale()
}

class User9: Drink {
    let name: String
    let type = "tea"
    var count = 0
    init(_ name: String){
        self.name = name
    }
    func Sale(){
        count += 1
        print("\(type): \(count)")
    }
}

let taro9 = User9("taro")
taro9.Sale()    //----- tean: 1
taro9.Sale()    //----- tean: 2
taro9.Sale()    //----- tean: 3    
            

エクステンション


// 計算プロパティのみ追加が可能
class User10 {
    let name: String
    init (_ name: String){
        self.name = name
    }
}

extension User10: Drink10 {
    var userName: String{
        return self.name
    }
    func sayHello(){
        print("Hello")
    }
}

protocol Drink10 {
    func sale()
}

extension Drink10 {
    func sale(){
        print("I sold it.")
    }
}

let taro10 = User10("taro")
print(taro10.userName)      //------ taro
taro10.sayHello()           //------ Hello
taro10.sale()               //------ I sold it.