有没有办法,使用泛型和类型约束,将此枚举的前两个案例合并为一个? enum AllowedValueRange { // Associated value represents (min, max). 'nil' represents // "no limit" for that interval end (+/- infinity) case Intege
enum AllowedValueRange { // Associated value represents (min, max). 'nil' represents // "no limit" for that interval end (+/- infinity) case IntegerRange(Int?, Int?) // Associated value represents (min, max). 'nil' represents // "no limit" for that interval end (+/- infinity) case FloatRange(Float?, Float?) // A finite set of specific values of any type case ArbitrarySet([Any]) // (...Other cases with different structure of associated values // or no associated values...) }
附录:
我知道我可以为整个枚举指定泛型类型,但只有这两种类型需要一个.此外,我认为它需要符合Equatable和Comparable,但我无法找到指定…的语法
编辑:事实证明Comparable包含Equatable(?),所以也许我可以这样做:
enum AllowedValueRange { // Associated value represents (min, max). 'nil' represents // "no limit" for that interval end (+/- infinity) case NumericRange((min:Comparable?, max:Comparable?)) // (rest omitted)
(还切换了一对关联值与单个,名为两个值的元组)
你可以定义enum AllowedValueRange { case NumericRange((min:Comparable?, max:Comparable?)) }
但这样可以让你用两个实例化一个值
例如,无关的可比类型
let range = AllowedValueRange.NumericRange((min: 12, max: "foo"))
这可能不是你想要的.所以你需要一个通用类型
(限于可比较):
enum AllowedValueRange<T: Comparable> { case NumericRange((min:T?, max:T?)) }