Casting a structure with a common parameter with fast

I am 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 a compilation error in the last line:

 'Car' is not identical to 'Vehicle' 

Is there any workaround for this?

I also believe that this type of casting should be possible, because I can do this with arrays that are based on generics. The following works:

 let carArray = Array<Car>() let vehicleArray = carArray as Array<Vehicle> 
+6
source share
1 answer

Quickly expanding an example array in a playground 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] 

I didnโ€™t work too much with fast generics, but quickly looked at quick documents.

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

and the use of vehicles instead of the general type T

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

appears to compile aok in the application (there are some problems with its processing on the playground)

0
source

Source: https://habr.com/ru/post/975521/


All Articles