下面的代码无法编译。我正在尝试将一个类发送到一个更改该类的函数,该类符合协议。该协议继承自另一个基本协议。我希望编译器知道 s (SportsCar) 符合 Car 但事实并非如此。
如果函数 test_car 不更改参数 car,则此代码有效。
谢谢
protocol Car {
var wheels: Int { get set }
}
protocol SportsCar : Car {
var engine: Int { get set }
}
class Test {
var p: Plunk
var s: SportsCar
init() {
print("Making Test")
p = Plunk()
s = p
}
func run() {
print("Running Test")
test_car(car: s ) // error: argument type 'SportsCar' does not conform to expected type 'Car'
print("Finished Test")
}
func test_car(car: inout Car) {
print("Car has \(car.wheels) wheels")
car.wheels += 1
print("Wheel added")
print("Car now has \(car.wheels) wheels\n")
}
}
class Plunk : SportsCar {
var wheels: Int
var engine: Int
var plunk: Bool
init(){
wheels = 4
engine = 1
plunk = true
}
}