Casting from array of protocol to array of parent protocol?

I'm trying to understand why this won't work:


protocol MyProtocol: AnyObject { }
let arrayOfMyProtocol: [MyProtocol] = []
let arrayOfAnyObject: [AnyObject] = arrayOfMyProtocol


Line 3 gives me the error "Cannot convert value of type `[MyProtocol]` to specified type `[AnyObject]`.

I can fix by changing the last line to:


let arrayOfAnyObject: [AnyObject] = arrayOfMyProtocol.map { $0 }


But I don't understand why or if it's really neccessary to creaete a new copy of the array.


Thanks,

Jesse

I guess answer is that Array<MyProtocol> doesn't inherit from Array<AnyObject> ... I was thinking of the contents as the type, not Array<Type>. Seems .map is the recommended solution.

[MyProtocol] and [AnyObject] have different representations (that is, the number of bytes per element is different, and the bytes have different information). That means you can't simply cast from one to the other: a value conversion is required. (Swift doesn't do value conversions at all, except in the sense that it can use "conversion" initializers, with the special-case exception of bridging, where there may be a value conversions as well as a type conversion.)

Casting from array of protocol to array of parent protocol?
 
 
Q