Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting struct with generic parameter with swift

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>
like image 856
hoddez Avatar asked Sep 19 '14 08:09

hoddez


1 Answers

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)

like image 143
Mark Essel Avatar answered Nov 08 '22 10:11

Mark Essel