我试图找出是什么让这件事发生了,但我失败了,有什么不对吗?
其他人是否遇到过这样的错误?
我该怎么做,我需要帮助
这是我的代码:
protocol MyProtocol {
}
struct MyStruct: MyProtocol {
}
let structs = [MyStruct(), MyStruct()]
var protocols = [MyProtocol]()
protocols = structs // it's ok
protocols += structs // this got an error
答案 0 :(得分:3)
在这一行上发生了编译魔术:
protocols = structs
循环遍历结构,将每个结构装入协议容器,然后执行赋值。它基本上执行此操作:
protocols = structs.map{ $0 as MyProtocol }
或等效地:
protocols = structs as [MyProtocol]
此编译器魔术不适用于+=
运算符。不过你可以自己做:
protocols += structs as [MyProtocol]