Swift 继承的协议发送到函数作为 inout
Swift inherited protocols sent to functions as inout
下面的代码无法编译。我正在尝试将 class 发送到更改 class 的函数,其中 class 符合协议。该协议继承自另一个基础协议。我希望编译器知道 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
}
}
I am trying to send a class to a function
你应该告诉编译器:
protocol Car: AnyObject { ... }
所以现在编译器知道 Car
的符合者将是 class
的一个实例。所以您不再需要 inout
关键字:
func test_car(car: Car) { ... }
下面的代码无法编译。我正在尝试将 class 发送到更改 class 的函数,其中 class 符合协议。该协议继承自另一个基础协议。我希望编译器知道 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
}
}
I am trying to send a class to a function
你应该告诉编译器:
protocol Car: AnyObject { ... }
所以现在编译器知道 Car
的符合者将是 class
的一个实例。所以您不再需要 inout
关键字:
func test_car(car: Car) { ... }