[ Swift ] Protocol を使って異なるクラスの同じメソッドを呼ぶ

protocol Vehicle {
    func start()
}

class Car: Vehicle {
    func start() {
        print("car > start")
    }
}
class Train: Vehicle {
    func start() {
        print("train > start")
    }
}

let car = Car()
let train = Train()
let vehicles:[Vehicle] = [car,train]
for obj in vehicles {
    obj.start() 
}


Extension を使って Protocol を拡張する事もできる。

extension Vehicle {
    func stop() {
        print("vehicle > stop")
    }
}

Related Contents

Pickup Contents