【发布时间】:2016-03-16 03:55:01
【问题描述】:
我正在尝试编写一个具有符合MyProto 的对象数组的类,并且我有一种方法可以在将[MyProto] 添加到该数组之前接受各种处理。这是一个游乐场。
protocol MyProto {
func sayHello()
}
extension MyProto {
func sayHello() {
print("hello")
}
}
struct MyStruct: MyProto {
}
class MyClass {
var protos: [MyProto] = []
func doSomethingAndThenStore(newProtos: [MyProto]) {
for proto in newProtos {
proto.sayHello()
}
protos.appendContentsOf(newProtos)
}
}
let myStructs = [MyStruct(), MyStruct()]
let myClass = MyClass()
myClass.doSomethingAndThenStore(myStructs)
在最后一行我得到一个错误,error: cannot convert value of type '[MyStruct]' to expected argument type '[MyProto]'。如果我将其更改为myStructs as [MyProto],则错误将更改为error: cannot convert value of type '[MyStruct]' to type '[MyProto]' in coercion。
如何将我的具体类型数组传递给接受协议数组的方法?
【问题讨论】:
标签: swift generics inheritance