在 Swift 协议中约束关联类型

Constraining associated types in Swift protocol

我正在编写一些代码片段来了解关联类型的工作原理,但我遇到了一个我不确定如何解释的错误。我写的代码贴在下面供参考。

// 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

解决方法是将 modify 函数中出现的所有 Doable 更改为 Element,如 Swift 文档中所述:Extensions with a Generic Where Clause .