Below I have pasted code which you should be able to paste into a Swift 3 playground and see the error.
I have a protocol defined and create an empty array of that t
append(_ newElement: Element)
appends a single element.
What you want is append(contentsOf newElements: C)
.
But you have
to convert the [MyClass]
array to [MyProtocol]
explicitly:
collection.append(contentsOf: myClassCollection as [MyProtocol])
// or:
collection += myClassCollection as [MyProtocol]
As explained in Type conversion when using protocol in Swift, this
wraps each array element into a box which holds "something that conforms to MyProtocol
", it is not just a reinterpretation
of the array.
The compiler does this automatically for a single value (that is why
for item in myClassCollection {
collection.append(item)
}
compiles) but not for an array. In earlier Swift versions, you
could not even cast an entire array with as [MyProtocol]
, you
had to cast each individual element.
Your trying to append an array when collection is only expecting individual items. For example, changing collection to this compiles:
var collection = [[MyProtocol]]()
here is a way you can go about adding two arrays together:
func merge<T: MyProtocol>(items: inout [T], with otherItems: inout [T]) -> [T] {
return items + otherItems
}
var myClassCollection = [MyClass(), MyClass()]
var myClassCollection2 = [MyClass(), MyClass()]
let combinedArray = merge(items: &myClassCollection, with: &myClassCollection2)