如何在协议中定义仅在协议的关联类型为特定类型时才需要实现的功能

时间:2019-10-07 12:14:14

标签: swift generics

我想在协议中定义一个具有关联类型的功能,只有在协议的关联类型遵循特定协议时才需要实现。

protocol Graph {
  associatedtype N:GraphNode

  // ... other functions

  // This method shall only need implementation if N:Equatable
  mutating func removeNode(_ node: N)
}

protocol GraphNode {
  var id: Int { get }
}

扩展允许添加特定情况下的功能,但也需要实现此功能,而我不想这样做。 所以这对我没有帮助:

extension Graph where N:Equatable {
  mutating func removeNode(_ node: N) {
    // Now I need to provide a default implementation
  }
}

我需要更多类似的东西:

protocol Graph {
  associatedtype N:GraphNode

  // ...

  mutating func removeNode(_ node: N) where N:Equatable
}

有什么办法吗?

提前谢谢! :)

1 个答案:

答案 0 :(得分:0)

经过进一步的研究,我相信没有“内置”的直接方法可以完成这样的事情。

我当前的解决方案如下:
基本协议:

protocol Graph {
  associatedtype N:GraphNode

  // ... other functions
}

protocol GraphNode {
  var id: Int { get }
}

另一种协议,其功能取决于相关类型的类型:

protocol RemovableNodes where Self:Graph, N:Equatable  {
    mutating func removeNode(_ node: N)
}

现在我们可以提供基本的实现:

class InMemoryGraph<N: GraphNode>: Graph {
  // blablabla here goes basic implementation for all defined functions
}

,以及如果N:Equatable:

是基本实现的扩展
extension InMemoryGraph:RemovableNodes where N:Equatable {
  func removeNode(_ node: N) {
    // implementation goes here
  }
}