swift - 如何在协议(protocol)中定义仅在协议(protocol)的关联类型为特定类型时才需要实现的函数

标签 swift generics

我想在协议(protocol)中定义函数,该协议(protocol)具有关联类型,仅当协议(protocol)的关联类型遵循特定协议(protocol)时才需要实现。

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
}

有什么办法吗?

提前致谢! :)

最佳答案

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

我目前的解决方案如下:
基本协议(protocol):

protocol Graph {
  associatedtype N:GraphNode

  // ... other functions
}

protocol GraphNode {
  var id: Int { get }
}

另一个包含依赖于关联类型类型的函数的协议(protocol):

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
  }
}

关于swift - 如何在协议(protocol)中定义仅在协议(protocol)的关联类型为特定类型时才需要实现的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58269350/

相关文章:

generics - 具有静态成员的 F# 泛型类型。这可能吗?

java - 将集合中的泛型类型与同一类型 java 进行比较

java - 为什么在用非泛型方法覆盖泛型方法时,子签名和未经检查的规则在返回类型上以这种方式工作?

java - 将 Java 泛型与特定类型结合使用

java - 在 GSON 中使用泛型

swift - 如何解决Xcode 8.3 beta中的 "String interpolation produces a debug description for an optional value; did you mean to make this explicit?"?

swift - 删除数组中多个索引处的项目

ios - Swift 嵌套堆栈 View

swift - 如何将 json 附加到自定义类数组中

ios - 使用 swift 启动应用程序时加载 admob 插页式广告