Apple Swift: Type Casting Generics

前端 未结 2 1330
别那么骄傲
别那么骄傲 2020-12-19 10:00

I\'m writing some Swift code where I have an array containing a generic type:

let _data: Array = T[]()

Later in my code I need to

2条回答
  •  轮回少年
    2020-12-19 10:22

    In swift, as operator is something like dynamic_cast in C++, which can be used to down cast an object.

    Say you have an object a of type A, and you can write let a as B only when type B is identical to type A, or B is a sub-class of A.

    In your case, apparently Array cannot always be down cast to Array or Array, so compiler reports errors.

    A simple fix is to convert to AnyObject first, and then downcast to Array or Array:

    let anyData: AnyObject = self._data;
    switch anyData {
    case let doubleData as? Array: // use as? operator, instead of as,
                                           // to avoid runtime exception
      // Do something with doubleData
    case let floatData as? Array:
      // Do something with floatData
    default:
      return nil // If the data type is unknown return nil
    

提交回复
热议问题