SLN SLN - 6 months ago 8
Swift Question

Error of creating an object of a protocol type which is inherited from multiple protocols

In the following code, there are 3 protocols:

Wheeled
,
Vehicle
and
WheeledVehicle
(inherited from
Wheeled
and
Vehicle
)

protocol Wheeled {
var numberOfWheels: Int { get }
}

protocol Vehicle {
var maker: String { get }
var owner: String {get set}
var ownerKid: String { get }
}

protocol WheeledVehicle: Wheeled, Vehicle {
// simply just combine Wheeled and Vehicle
}

class Bike: Vehicle, Wheeled {
let numberOfWheels: Int = 0
var ownerKid: String = "Junior"

var maker: String {
return "Ford"
}

var owner: String {
get {
return "Bob"
}
set {
ownerKid = "\(newValue) Junior"
}
}
}


let bike: Bike = Bike()

let wheeledVehicleBike: WheeledVehicle = bike //error: value of type 'Bike' does not conform to specified type 'WheeledVehicle'


Question: Pretty much the error itself, I don't get it, why value of type
Bike
does not conform to specified type
WheeledVehicle


Thanks a lot for your time and help.

Answer

Basically: Because it does not conform to it

For the compiler to know that Bike conforms to WheeledVehicle you have to specify that. The compiler will not just assume that since both conform to the same protocols they can be assigned to each other.

The same way that the following does not work.

class A { var a : String = "" }
class B { var a : String = "" }

var a : A = A()
var b : B = a // cannot convert value of type 'A' to specified type 'B'

Or even simpler

class A {  }
class B {  }

var a : A = A()
var b : B = a // cannot convert value of type 'A' to specified type 'B'

The compiler does not care if the two types look alike - they have to be alike.

What would happen in your example if your WheeledVehicle gets a func added? Does Bike no longer conform to it?

The only way to make Bike conform to WheeledVehicle is to declare it explicitly: class Bike : WheeledVehicle!