Search code examples
iosswiftprotocolshashableequatable

Swift Protocols: can I restrict associated types?


I have set of protocols:

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

Is it possible to restrict SpaceInterpolatorProtocol definition that

Axis == Spot.Axis
Axis.CoordUnit == Spot.Axis.CoordUnit
Vertex.Spot == Spot

and not to use where in all protocol extensions?


Solution

  • Those aren't restrictions, they're just aliases, so you can express them as aliases:

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

    Unrelated code review, ignore if you like: This does not look like a good use of protocols, and feels likely to cause a lot of problems and excessive type-erasure, but aligning the types is no issue. I would probably replace all of these with concrete structs, and look for places code duplicates, but that's unrelated to the question. The simplification of the associatedtypes down to a single type suggests the top level struct should be SpaceInterpolator<CoordUnit: FloatingPoint>.