【发布时间】:2015-12-03 07:35:18
【问题描述】:
有没有办法使用泛型和类型约束将enum 的前两种情况合并为一个?
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...)
}
附录:
我知道我可以为整个enum 指定一个泛型类型,但只有这两种类型需要一个。另外,我认为它需要同时符合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)
(也将一对关联值与单个命名的两个值的元组切换)
【问题讨论】: