possen possen - 1 year ago 152
Swift Question

Swift Protocol Arrays Adding vs. Instantiating

In swift 3.0 Xcode beta 3, I defined a fairly simple protocol and two structs that implement it, if I initialize the array when creating the objects, it works, but if I try to add elements I get an error:

Cannot convert value of type '[H]' to expected argument type 'inout _'

Shouldn't this work?

protocol H {
var v : Int { get set }
func hello()

struct J : H {
var v : Int
func hello() {

struct K : H {
var v : Int
func hello() {

let ag:[H] = [K(v:3), J(v:4)] // works

var af:[H] = []
af += [K(v:3)] // does not work
af += [J(v:4)] // does not work

Answer Source

It's a type issue. You need the things you add to af to be the same type as af, namely [H]:

var af:[H] = []
let arr1:[H] = [K(v:3)]
let arr2:[H] = [J(v:4)]
af += arr1
af += arr2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download