2016-07-24 35 views
-1

這是演示此問題的一些演示代碼。無法附加到結構中的自定義協議數組 - Swift

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

如果數組是在Struct之外創建的,我可以追加。但在Struct內部,會發生此錯誤。

+0

它不會「拋出錯誤」。它根本不會編譯。 – matt

回答

1

您的錯誤是預期聲明

你不能在結構中有自由浮動的代碼。它需要在一個函數內:

protocol Test {} 

struct Conforms: Test {} 

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

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

var testing = Testing() 
testing.foo()