使用协议扩展的默认关联类型

Ayu*_*oel 6 swift swift-protocols protocol-extension

我有一个带有associatedType. 我想typealias在协议扩展中为该类型提供一个默认值。这仅适用于从特定类继承的类。

protocol Foo: class {
  associatedtype Bar
  func fooFunction(bar: Bar)
}
Run Code Online (Sandbox Code Playgroud)

协议扩展:

extension Foo where Self: SomeClass {
  typealias Bar = Int
  func fooFunction(bar: Int) {
    // Implementation
  }
}
Run Code Online (Sandbox Code Playgroud)

编译器抱怨'Bar' is ambiguous for type lookup in this context. 我也无法在 swift 书中找到任何有用的东西。

Khu*_*pan -1

扩展上下文中有两个可用的关联类型 Bar,编译器无法推导出正确的一个。尝试这个。

protocol Foo: class {
  associatedtype Bar
  func fooFunction(bar: Bar)
}

extension Foo where Self: SomeClass {
  func fooFunction(bar: SomeClass.Bar) {}
}

class SomeClass:Foo{
  typealias Bar = Int
}
Run Code Online (Sandbox Code Playgroud)