Home > other >  Swift inherited protocols sent to functions as inout
Swift inherited protocols sent to functions as inout

Time:11-14

The code below does not compile. I am trying to send a class to a function that changes that class, where the class conforms to a protocol. This protocol inherits from another base protocol. I would expect the compiler to know that s (SportsCar) conforms to Car but it doesn't.

This code works if the function test_car does not change the argument car.

Thanks

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
    }

}

CodePudding user response:

I am trying to send a class to a function

You should tell that to the compiler:

protocol Car: AnyObject { ... }

So now the compiler knows that the conformer to the Car would be an instance of a class. So you don't need the inout keyword anymore:

func test_car(car: Car) { ... }
  • Related