Swift协议扩展实现具有共享关联类型的另一协议

Dan*_*hin 6 associated-types swift swift2 protocol-extension

考虑以下:

protocol Foo {
  typealias A
  func hello() -> A
}
protocol FooBar: Foo {
  func hi() -> A
}
extension FooBar {
  func hello() -> A {
    return hi()
  }
}

class FooBarClass: FooBar {
  typealias A = String
  func hi() -> String {
    return "hello world"
  }
}
Run Code Online (Sandbox Code Playgroud)

这段代码编译.但是如果我注释掉关联类型的显式定义typealias A = String,那么由于某种原因,swiftc无法推断出类型.

我感觉这与两个共享相同关联类型但没有直接断言的协议有关,例如,类型参数化(可能关联类型不够强大/不够成熟?),这使得类型推断模糊不清.

我不确定这是否是该语言的错误/不成熟,或者可能,我错过了协议扩展中的一些细微差别,这恰恰导致了这种行为.

有人可以对此有所了解吗?

Pat*_*ley 0

为了符合所述协议,需要为协议中的关联类型提供显式值。这可以通过对类型进行硬编码来完成,就像您对 所做的那样typealias A = String,或者使用您提到的参数化类型,如下所示:

class FooBarClass<T>: FooBar {
    typealias A = T
    ...
}
Run Code Online (Sandbox Code Playgroud)

Swift 不会从协议的实现方法中推断出关联类型,因为多个类型不匹配的方法可能会产生歧义。这就是为什么必须在实现类中显式解析类型别名的原因。