问题描述
考虑这个枚举:
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(describing: self)
.(因为 String(describing: self)
正在使用 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)
这篇关于比较两个枚举变量,而不考虑它们的关联值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!