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<T>
cannot always be down cast to Array<Double>
or Array<Float>
, so compiler reports errors.
A simple fix is to convert to AnyObject
first, and then downcast to Array<Double>
or Array<Float>
:
let anyData: AnyObject = self._data;
switch anyData {
case let doubleData as? Array<Double>: // use as? operator, instead of as,
// to avoid runtime exception
// Do something with doubleData
case let floatData as? Array<Float>:
// Do something with floatData
default:
return nil // If the data type is unknown return nil
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…