2017-04-02 85 views
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) 
    } 
} 

我已经做了约束MyTypeDoable,但编译器抱怨说,它不能转换(Array<Self.MyType>) -> Array<Self.MyType> to expected argument type (Array<Doable>) -> Array<Doable>。任何人都可以解释一下这里发生了什么,以及我如何让编译器高兴?

回答

1

如错误消息所示,modify函数需要类型为Array<Doable>的参数,并且您传递的参数类型为Array<MyType>

问题从modify定义,在那里你明确的参数使用Doable,排除所有其他类型,但Doable茎 - 和相关类型不是类型别名,MyType不能转换为Doable

修复的方法是改变Doable所有出现在modify功能Element,随着斯威夫特文档中被描绘:Extensions with a Generic Where Clause

+0

优秀的解释。感谢您的链接了。这就是我喜欢SO的原因。 – Erik