繁体   English   中英

Swift 继承的协议发送到函数作为 inout

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM