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

后端 未结 2 1617
不知归路
不知归路 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

    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(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)
    

提交回复
热议问题