繁体   English   中英

具有约束的泛型类型的关联值的枚举案例

[英]Enum case with associated value of generic type with constraints

有没有办法,使用泛型和类型约束,将此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指定泛型类型,但只有这两种类型需要一个。 此外,我认为它需要符合EquatableComparable ,但我无法找到指定...的语法


编辑:事实证明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?))
}

暂无
暂无

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

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