EDIT: This works absolutely fine in Swift 3, which we should all be using by now :)
If I have two protocols, X and Y where Y implements X, why can't I assign an array of Y to a variable with the type [X]?
Even more curiously, I can convert it one by one into an array of X, and that compiles fine.
protocol X { }
protocol Y: X { }
// Make a test array of Y
extension String: Y { }
let a: [Y] = [ "Hello" ]
// Make it into an array of X - this works absolutely fine
let b: [X] = [ a[0] as X ]
// Why won't this cast work?
let c: [X] = a as [X]
I thought that given Y does everything X can do, this assignment should be fine (yea, I lose some type information, but it should at least compile!)
Any ideas?
EDIT: The current answer points out that it's a dangerous thing to do if you are using mutable arrays - which I didn't get but do now :) However, if my arrays are all immutable why won't Swift let this happen? Even if c is a mutable array (i.e. var c = a as [X]) why won't Swift copy it, leaving a intact?
Zto the hierarchy which also derives from X. Now your Array has bothYandZ, even thoughZis not a subtype ofY.Y. E.g.struct Z: X {};b.append(Z()). Nowbdoes contain an element of typeStringand an element of typeZ. And the compiler is fine with that.