Swift 3 unable to append array of objects, which conform to a protocol, to a collection of that protocol

后端 未结 2 1622
不知归路
不知归路 2020-12-07 03:05

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

2条回答
  •  旧时难觅i
    2020-12-07 03:44

    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.

提交回复
热议问题