Swift 带有泛型类型与约束的关联值的枚举事例
有没有办法使用泛型和类型约束将此Swift 带有泛型类型与约束的关联值的枚举事例,swift,generics,enums,Swift,Generics,Enums,有没有办法使用泛型和类型约束将此enum的前两种情况合并为一种 enum AllowedValueRange { // Associated value represents (min, max). 'nil' represents // "no limit" for that interval end (+/- infinity) case IntegerRange(Int?, Int?) // Associated value represents (m
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
指定泛型类型,但只有这两种类型需要一种。此外,我认为它需要同时符合equalable
和compariable
,但我找不到语法来指定
编辑:结果是
可比较的包含可平等的(?),所以也许我可以这样做:
enum AllowedValueRange {
// Associated value represents (min, max). 'nil' represents
// "no limit" for that interval end (+/- infinity)
case NumericRange((min:Comparable?, max:Comparable?))
// (rest omitted)
(还将一对关联值与两个值的命名元组进行切换)您可以定义
但这将允许您用两个参数实例化一个值
例如,不相关的可比类型
let range = AllowedValueRange.NumericRange((min: 12, max: "foo"))
这可能不是你想要的。所以你需要一个泛型类型
(仅限于可比性):
enum AllowedValueRange{
案例编号范围(最小:T?,最大:T?)
}
我明白了。我唯一不喜欢这个解决方案的地方是,在任何其他情况下,我都不需要t
;我希望我能只为numeriRange
而不是整个enum
声明它。我想这是我能得到的最好的了。也就是说,我希望声明:enum AllowedValueRange{case numeriRange((min:T?,max:T?)/*…*/}
@NicolasMiari:我明白了,但我认为这是不可能的。
let range = AllowedValueRange.NumericRange((min: 12, max: "foo"))
enum AllowedValueRange<T: Comparable> {
case NumericRange((min:T?, max:T?))
}