swift - 在 Swift 协议(protocol)中约束关联类型

标签 swift swift-protocols

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

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

解决方法是更改​​所有出现的 Doablemodify功能Element ,如 Swift 文档中所述:Extensions with a Generic Where Clause .

关于swift - 在 Swift 协议(protocol)中约束关联类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43168215/

相关文章:

ios - 从 UIView 转换后的 PDF 不完整

具有关联类型和影子类型删除的 Swift 协议(protocol)

ios - 如何添加动态部分但仍然只添加到其中一个部分?

ios - GameplayKit > Scene Editor Navigation Graph > 如何使用它来寻路?

ios - 成功登录后打开标签栏 Controller swift

swift 2 : How to refer to a type of an element in default implementation of a function in a protocol

swift - 在 swift 中,如何返回符合协议(protocol)的相同类型的对象

swift - 我想在 ARKit 中制作图像列表,但无法返回它

c - 获取协议(protocol)中方法 block 的 NSMethodSignature

swift - 将协议(protocol)方法标记为已弃用