我想在协议(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/