ios – 使用swift将通用参数转换为struct

前端之家收集整理的这篇文章主要介绍了ios – 使用swift将通用参数转换为struct前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试做以下事情.
  1. protocol Vehicle {
  2.  
  3. }
  4.  
  5. class Car : Vehicle {
  6.  
  7. }
  8.  
  9. class VehicleContainer<V: Vehicle> {
  10.  
  11. }
  12.  
  13. let carContainer = VehicleContainer<Car>()
  14. let vehicleContainer = carContainer as VehicleContainer<Vehicle>

但是我在最后一行得到了编译错误

  1. 'Car' is not identical to 'Vehicle'

这有什么解决方法吗?

另外我认为这种类型的转换应该是可能的,因为我可以使用基于泛型的数组来实现.以下作品:

  1. let carArray = Array<Car>()
  2. let vehicleArray = carArray as Array<Vehicle>

解决方法

在游乐场快速扩展您的数组示例按预期工作
  1. protocol Vehicle {
  2.  
  3. }
  4.  
  5. class Car : Vehicle {
  6.  
  7. }
  8.  
  9. class Boat: Vehicle {
  10.  
  11. }
  12.  
  13. var carArray = [Car]()
  14. var vehicleArray : [Vehicle] = carArray as [Vehicle]
  15. vehicleArray.append(Car()) // [__lldb_expr_183.Car]
  16. vehicleArray.append(Boat()) // [__lldb_expr_183.Car,__lldb_expr_183.Boat]

没有用快速的仿制药做太多的工作,但快速查看swift docs

  1. struct Stack<T: Vehicle> {
  2. var items = [Vehicle]()
  3. mutating func push(item: Vehicle) {
  4. items.append(item)
  5. }
  6. mutating func pop() -> Vehicle {
  7. return items.removeLast()
  8. }
  9. }

并使用车辆而不是通用类型T.

  1. var vehicleStack = Stack<Vehicle>()
  2. vehicleStack.push(Car())
  3. vehicleStack.push(Boat())
  4. var aVehicle = vehicleStack.pop()

似乎在应用程序中编译aok(操场上有一些问题处理它)

猜你在找的iOS相关文章