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
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