[英]Swift inherited protocols sent to functions as inout
下面的代碼不能編譯。 我正在嘗試將一個類發送到一個更改該類的函數,其中該類符合協議。 該協議繼承自另一個基本協議。 我希望編譯器知道 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
}
}
我正在嘗試將一個類發送到一個函數
你應該告訴編譯器:
protocol Car: AnyObject { ... }
所以現在編譯器知道Car
的conformer 將是一個class
的實例。 所以你不再需要inout
關鍵字了:
func test_car(car: Car) { ... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.