7

I'm trying to do the following.

protocol Vehicle {

}

class Car : Vehicle {

}

class VehicleContainer<V: Vehicle> {

}

let carContainer = VehicleContainer<Car>()
let vehicleContainer = carContainer as VehicleContainer<Vehicle>

But I get the compile error on the last line:

'Car' is not identical to 'Vehicle' 

Is there any workaround for this?

Also I believe this type of casting should be possible because I can do it with Arrays which are built on generics. The following works:

let carArray = Array<Car>()
let vehicleArray = carArray as Array<Vehicle>
3
  • Not sure if this has anything to do with it, but Array is a value type. Try to reformulate your above hierarchy in terms of structs and see if you still get the same error. Commented Sep 19, 2014 at 8:13
  • Yeah I tried that already with VehicleContainer as a Struct and it gives the same error Commented Sep 20, 2014 at 9:55
  • Not really. I think you aren't even really supposed to be able to convert arrays like I showed. If you add elements it doesn't seem to work Commented Mar 20, 2015 at 13:28

1 Answer 1

1

Expanding your array example quickly in playground works as intended

protocol Vehicle {

}

class Car : Vehicle {

}

class Boat: Vehicle {

}

var carArray = [Car]()
var vehicleArray : [Vehicle] = carArray as [Vehicle]
vehicleArray.append(Car())  // [__lldb_expr_183.Car]
vehicleArray.append(Boat()) // [__lldb_expr_183.Car, __lldb_expr_183.Boat]

Haven't done too much work with swift generics but looking quickly at the swift docs

struct Stack<T: Vehicle> {
    var items = [Vehicle]()
    mutating func push(item: Vehicle) {
        items.append(item)
    }
    mutating func pop() -> Vehicle {
        return items.removeLast()
    }
}

and using vehicles instead of the generic type T

var vehicleStack = Stack<Vehicle>()
vehicleStack.push(Car())
vehicleStack.push(Boat())
var aVehicle = vehicleStack.pop()

appears to compile aok in an app (playground has some issues handling it though)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.