加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:33:42 所属栏目:百科 来源:网络整理
导读:有没有办法,使用泛型和类型约束,将此枚举的前两个案例合并为一个? enum AllowedValueRange { // Associated value represents (min,max). 'nil' represents // "no limit" for that interval end (+/- infinity) case IntegerRange(Int?,Int?) // Associate
有没有办法,使用泛型和类型约束,将此枚举的前两个案例合并为一个?

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读