比较两个枚举变量,无论其关联值如何 [英] Comparing two enum variables regardless of their associated values

查看:218
本文介绍了比较两个枚举变量,无论其关联值如何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个枚举:

enum DataType {
    case One (data: Int)
    case Two (value: String)
}

Swift具有模式匹配功能,可将枚举与关联的枚举进行比较值,如下所示:

Swift has pattern matching to compare an enum with associated values, like so:

let var1 = DataType.One(data: 123)
let var2 = DataType.One(data: 456)

if case DataType.One(data: _) = var2 {
    print ("var2 is DataType.One")
}

如何比较一个变量和一个枚举类型而不是比较两个变量的枚举类型? 我看到了很多类似的问题,但是没有一个问题集中在您有两个变量的情况下。

How would one go about comparing not one variable against an enum type, but comparing the enum type of two variables? I saw a ton of similar questions, but none focused on the case where you have two variables.

我基本上想要的是:

if case var1 = var2 {
    print ("var1 is the same enum type as var2")
}


推荐答案

更新的方法:

我认为没有障碍我为此提供支持。但是,您可以通过定义自定义运算符来实现此目的(最好使用协议,但也可以直接执行此操作)。像这样的东西:

I think there's no native support for this. But you can achieve it by defining a custom operator (preferrably by using a protocol, but you can do it directly as well). Something like this:

protocol EnumTypeEquatable {
    static func ~=(lhs: Self, rhs: Self) -> Bool
}

extension DataType: EnumTypeEquatable {
    static func ~=(lhs: DataType, rhs: DataType) -> Bool {
        switch (lhs, rhs) {
        case (.one, .one), 
             (.two, .two): 
            return true
        default: 
            return false
        }
    }
}

然后像这样使用它:

let isTypeEqual = DataType.One(value: 1) ~= DataType.One(value: 2)
print (isTypeEqual) // true




旧方法:

protocol EnumTypeEquatable {
    var enumCaseIdentifier: String { get }
}

extension DataType: EnumTypeEquatable {
    var enumCaseIdentifier: String {
        switch self {
        case .one: return "ONE"
        case .two: return "TWO"
        }
    }
}

func ~=<T>(lhs: T, rhs: T) -> Bool where T: EnumTypeEquatable {
    return lhs.enumCaseIdentifier == rhs.enumCaseIdentifier
}

较早的版本取决于运行时,并可能提供默认的 enumCaseIdentifier 实现,具体取决于 String(描述:自我)不推荐使用。 (因为 String(描述:自我)正在使用 CustromStringConvertible 协议,并且可以更改)

The older version depends on Runtime and might be provided with default enumCaseIdentifier implementation depending on String(describing: self) which is not recommended. (since String(describing: self) is working with CustromStringConvertible protocol and can be altered)

这篇关于比较两个枚举变量,无论其关联值如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆