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

后端 未结 2 1615
不知归路
不知归路 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条回答
  • 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.

    0 讨论(0)
  • 2020-12-07 03:44

    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)
    
    0 讨论(0)
提交回复
热议问题