Chapter 17 - Protocols

Hi students,

does anyone know why I have this error “Cannot convert value of type ‘[any Vehicle.Type]’ to expected argument type ‘[any Vehicle]’” with my code:

protocol Vehicle {
    
    // the abstract form of the vehicle
    func describe() -> String

    mutating func accelerate()
    mutating func stop()
    
    var speed : Double { get set }
    static var maxSpeed : Double { get }
}

class Unicycle : Vehicle {
        
    func describe() -> String {
        return "Unicycle @ \(speed) mph"
    }
    func accelerate() {
        speed = min(speed + 2, Self.maxSpeed)
    }
    func stop() {
        speed = 0
    }
    
    var speed : Double = 0
    static var maxSpeed : Double { 15 }
    
}

struct Car {
    
    func describe() -> String {
        return "Car @ \(speed) mph"
    }
    
    mutating func accelerate() {
        speed = min(speed + 20, Self.maxSpeed)
    }
    mutating func stop() {
        speed = 0
    }
    var speed : Double = 0
    static var maxSpeed : Double { 150 }
    
}

extension Car : Vehicle {}

extension Vehicle {
    
    mutating func stop() {
        speed = 0
    }
    
    var normalizedSpeed : Double {
        return speed / Self.maxSpeed
    }
    
}

let vehicleC : Vehicle.Type = Unicycle.self
print("Vehicle :: \(vehicleC)")

let vehicleS : Vehicle.Type = Car.self
print("Vehcile -> Car :: \(vehicleS)")

var vehicles : [Vehicle.Type] = [vehicleC.self, vehicleS.self]

func stop(vehiclesA: inout [any Vehicle]) {
  vehiclesA.indices.forEach {
    vehiclesA[$0].stop()
  }
}

stop(vehiclesA : &vehicles)```

Hello,

In your code near the end, the variables vehicleC and vehicleS are not defined properly. Their type should be Vehicle and not Vehicle.Type, and the instance should be Car() or Unicycle().

The code should look like this:

let vehicleC : Vehicle = Unicycle()
print("Vehicle :: \(vehicleC)")

let vehicleS : Vehicle = Car()
print("Vehcile -> Car :: \(vehicleS)")

var vehicles : [Vehicle] = [vehicleC, vehicleS]

func stop(vehiclesA: inout [any Vehicle]) {
  vehiclesA.indices.forEach {
    vehiclesA[$0].stop()
  }
}

stop(vehiclesA : &vehicles)