下面的代碼不能編譯。我正在嘗試將一個類發送到一個更改該類的函式,其中該類符合協議。該協議繼承自另一個基本協議。我希望編譯器知道 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
}
}
uj5u.com熱心網友回復:
我正在嘗試將一個類發送到一個函式
你應該告訴編譯器:
protocol Car: AnyObject { ... }
所以現在編譯器知道 的符合者Car將是 a 的實體class。所以你不再需要inout關鍵字:
func test_car(car: Car) { ... }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/362182.html
