[英]Swift Protocols: can I restrict associated types?
我有一套协议:
protocol SpaceInterpolatorProtocol {
associatedtype Axis: SpaceAxisProtocol
associatedtype Spot: SpaceAxisSpotProtocol
associatedtype Vertex: SpaceVertexProtocol
....
}
protocol SpaceAxisProtocol: Equatable & Hashable {
associatedtype CoordUnit: FloatingPoint
...
}
protocol SpaceVertexProtocol:Hashable {
associatedtype Spot: SpaceAxisSpotProtocol
...
}
protocol SpaceAxisSpotProtocol : Hashable {
associatedtype Axis: SpaceAxisProtocol
...
}
是否可以限制 SpaceInterpolatorProtocol 定义
Axis == Spot.Axis
Axis.CoordUnit == Spot.Axis.CoordUnit
Vertex.Spot == Spot
而不是在所有协议扩展中使用where
?
这些不是限制,它们只是别名,因此您可以将它们表示为别名:
protocol SpaceInterpolatorProtocol {
associatedtype Vertex: SpaceVertexProtocol
typealias Spot = Vertex.Spot
typealias Axis = Spot.Axis
}
不相关的代码审查,喜欢就忽略:这看起来不像是很好地使用协议,并且感觉可能会导致很多问题和过度的类型擦除,但是对齐类型是没有问题的。 我可能会用具体的结构替换所有这些,并寻找代码重复的地方,但这与问题无关。 将关联类型简化为单一类型表明顶级结构应该是SpaceInterpolator<CoordUnit: FloatingPoint>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.