我正在编写一些代码片段来了解关联类型的工作原理,但我遇到了一个我不确定如何解释的错误。我写的代码贴在下面供引用。
// 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>
.任何人都可以解释这里发生了什么以及我如何才能让编译器满意吗?
最佳答案
如错误消息所述,modify
函数需要类型为 Array<Doable>
的参数并且您正在传递类型为 Array<MyType>
的参数.
问题源于 modify
的定义,您明确使用 Doable
的地方在参数中,排除所有其他类型,但 Doable
– 由于关联类型不是类型别名,MyType
无法转换为 Doable
.
解决方法是更改所有出现的 Doable
在modify
功能Element
,如 Swift 文档中所述:Extensions with a Generic Where Clause .
关于swift - 在 Swift 协议(protocol)中约束关联类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43168215/