【问题标题】:Enum case with associated value of generic type with constraints具有约束的泛型类型关联值的枚举案例
【发布时间】: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)

(也将一对关联值与单个命名的两个值的元组切换)

【问题讨论】:

    标签: swift generics enums


    【解决方案1】:

    你可以定义

    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?))
    }
    

    【讨论】:

    • 我明白了。我唯一不喜欢这个解决方案的是,我真的不需要 T 在任何其他 cases 中;我希望我只能为NumericRange 而不是整个enum 声明它。我想这是我能得到的最好的了。
    • 也就是说,我希望声明是合法的:enum AllowedValueRange { case NumericRange&lt;T: Comparable&gt;((min:T?, max:T?)) /* ... */ }
    • @NicolasMiari:我明白了,但我认为这是不可能的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    相关资源
    最近更新 更多