Brandon Bradley Brandon Bradley - 4 months ago 15
Swift Question

Can't Append to Array of Custom Protocol in Struct - Swift

This is some demo code that demonstrates the issue.

protocol Test {}
struct Conforms: Test {}
struct Testing {
var t: [Test]
//The following throws an error
t.append(Conforms())
}


If the array is created outside of the Struct, I am able to append. Inside the Struct however, this error occurs.

Answer

Your error is Expected Declaration.

You can't have free floating code in a structure. It needs to be inside of a function:

protocol Test {}

struct Conforms: Test {}

struct Testing {
    var t: [Test] = []

    mutating func foo() {
        t.append(Conforms())
    }
}

var testing = Testing()
testing.foo()