简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM