1
我正在编写一些代码片段,以了解关联类型如何工作,但我遇到了一个错误,我不知道如何解释。我写的代码发布在下面供参考。在Swift协议中约束关联的类型
// A basic protocol
protocol Doable {
func doSomething() -> Bool
}
// An extension that adds a method to arrays containing Doables
extension Array where Element: Doable {
func modify(using function:(Array<Doable>)->Array<Doable>) -> Array<Doable> {
return function(self)
}
}
// Another protocol with an associated type constrained to be Doable
protocol MyProtocol {
associatedtype MyType: Doable
func doers() -> Array<MyType>
func change(_:Array<MyType>) -> Array<MyType>
}
// An simple extension
extension MyProtocol {
func modifyDoers() -> Array<MyType> {
return doers().modify(using: change)
}
}
我已经做了约束MyType
是Doable
,但编译器抱怨说,它不能转换(Array<Self.MyType>) -> Array<Self.MyType> to expected argument type (Array<Doable>) -> Array<Doable>
。任何人都可以解释一下这里发生了什么,以及我如何让编译器高兴?
优秀的解释。感谢您的链接了。这就是我喜欢SO的原因。 – Erik