【问题标题】:Default associatedType using protocol extension使用协议扩展的默认关联类型
【发布时间】:2016-05-28 07:22:04
【问题描述】:

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

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

协议扩展:

extension Foo where Self: SomeClass {
  typealias Bar = Int
  func fooFunction(bar: Int) {
    // Implementation
  }
}

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

【问题讨论】:

    标签: swift swift-protocols protocol-extension


    【解决方案1】:

    刚刚遇到同样的问题,并且使用 Swift 4(也许在早期版本中,我还没有测试过),您可以在其定义中为您的 associatedtype 添加一个默认值:

    protocol Foo: class {
      associatedtype Bar = Int  // notice the "= Int" here
      func fooFunction(bar: Bar)
    }
    

    无需为此向您的协议添加扩展。

    (我在文档中找不到任何提及这一点,但它对我来说按预期工作,并且这样写似乎很自然。如果您可以链接到一些有信誉的来源,请随时在答案中编辑它)

    【讨论】:

      【解决方案2】:

      在扩展上下文中有两个关联类型 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
      }
      

      【讨论】:

      • 这正是我不想做的。我希望我的类只符合协议并根据它的类型获得默认实现。
      • 顺便说一句,你可以在你的协议实现中简单地说func fooFunction(bar: Bar) {}。它会自动选择符合标准的类的关联类型。不需要SomeClass.Bar
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-17
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多