【问题标题】:How to define a function in a protocol which needs only implemented if the protocol's associatedtype is of specific type如何在协议中定义仅在协议的关联类型为特定类型时才需要实现的功能
【发布时间】:2019-10-07 12:14:14
【问题描述】:

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

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
}

有什么办法吗?

提前致谢! :)

【问题讨论】:

    标签: swift generics


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 2019-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多