简体   繁体   English

Swift 协议:我可以限制关联类型吗?

[英]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是否可以限制 SpaceInterpolatorProtocol 定义

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

and not to use where in all protocol extensions?而不是在所有协议扩展中使用where

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> .将关联类型简化为单一类型表明顶级结构应该是SpaceInterpolator<CoordUnit: FloatingPoint>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Swift中具有关联类型的协议的问题 - Issue with Protocols with Associated Types in Swift 协议上的关联类型和泛型 - Associated types and generics on protocols 具有关联类型要求和默认实现的Swift协议 - Swift Protocols with Associated Type Requirement and Default Implementation 如何在 swift 的方法参数中实现协议? - How can I implement protocols in method parameters in swift? Swift中通用类型的工厂(协议和泛型) - Factory of generic types in Swift (Protocols and generics) 在 swift 中使用协议作为数组类型和函数参数 - Usage of protocols as array types and function parameters in swift 具有关联类型和泛型的Swift协议调用了错误的函数 - Swift Protocols with Associated Type and Generics calling wrong function Swift 协议在 function 中具有相互递归关联的类型约束 - Swift protocols with mutually recursive associated type constraints in a function 将协议与关联对象绑定-使用Swift进行面向协议的编程 - Binding Protocols with Associated Objects - Protocol Oriented Programming with Swift swift 将字典转换为 jsonString 错误:协议类型 'Any' 不能符合 'Encodable' 因为只有具体类型才能符合协议 - swift Convert dictionary to jsonString error : Protocol type 'Any' cannot conform to 'Encodable' because only concrete types can conform to protocols
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM