【问题标题】:Swift Protocols: can I restrict associated types?Swift 协议:我可以限制关联类型吗?
【发布时间】:2020-05-15 12:06:16
【问题描述】:

我有一套协议:

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

【问题讨论】:

    标签: ios swift protocols hashable equatable


    【解决方案1】:

    这些不是限制,它们只是别名,因此您可以将它们表示为别名:

    protocol SpaceInterpolatorProtocol {
        associatedtype Vertex: SpaceVertexProtocol
        typealias Spot = Vertex.Spot
        typealias Axis = Spot.Axis
    }
    

    不相关的代码审查,如果你喜欢忽略: 这看起来不是很好地使用协议,并且感觉可能会导致很多问题和过多的类型擦除,但是对齐类型是没有问题的。我可能会用具体的结构替换所有这些,并寻找代码重复的地方,但这与问题无关。将关联类型简化为单一类型表明顶级结构应为SpaceInterpolator<CoordUnit: FloatingPoint>

    【讨论】:

    • 谢谢!这正是我所寻找的。并感谢您的建议!
    猜你喜欢
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多