Let's say I have the following:
protocol MyProtocol {
}
struct MyStruct: MyProtocol {
}
var s1 = MyStruct()
var s2 = MyStruct()
var s3 = MyStruct()
var structArray = [s1, s2, s3]
When I try to assign this array of structs to an array of protocols (that each struct in structArray conforms to):
var protocolArray:[MyProtocol] = structArray
I get this error: Cannot convert array of type '[MyStruct]' to specified type '[MyProtocol]'
I would expect that since each object in the array conforms to the protocol it would be ok to say that "an array of structs that conform to some protocol" is assignable to something that expects "an array of anything that conforms to that protocol". But maybe this doesn't apply when the type is "an array of " vs just "thing", if that makes any sense.
For example, this is valid:
var p1:MyProtocol = s1
Because s1 conforms to MyProtocol. But if you use arrays then it doesn't seem to hold anymore.
Incidentally, this seems to work too:
var p1Array:[MyProtocol] = [s1, s2, s3]
Presumably because the type of the array is determined to be [MyProtocol] and isn't predetermined by some previous variable (like in my example above).
So anyways, all this to ask: What's the best way around this? How can I assign an array of structs (that conform to some protocol) to another array whose type is just "an array of things that conform that protocol".
I'm fairly new to Swift so I may be missing something trivial.