如何通过忽略 Swift 中的关联值来比较枚举与关联值?
阅读如何测试Swift枚举的相等性使用关联值,我实现了以下枚举:
After reading How to test equality of Swift enums with associated values, I implemented the following enum:
enum CardRank {
case Number(Int)
case Jack
case Queen
case King
case Ace
}
func ==(a: CardRank, b: CardRank) -> Bool {
switch (a, b) {
case (.Number(let a), .Number(let b)) where a == b: return true
case (.Jack, .Jack): return true
case (.Queen, .Queen): return true
case (.King, .King): return true
case (.Ace, .Ace): return true
default: return false
}
}
以下代码有效:
let card: CardRank = CardRank.Jack
if card == CardRank.Jack {
print("You played a jack!")
} else if card == CardRank.Number(2) {
print("A two cannot be played at this time.")
}
但是,这不会编译:
let number = CardRank.Number(5)
if number == CardRank.Number {
print("You must play a face card!")
}
... 并给出以下错误消息:
... and it gives the following error message:
二元运算符'=='不能应用于'CardRank'和'(Int) -> CardRank'类型的操作数
Binary operator '==' cannot be applied to operands of type 'CardRank' and '(Int) -> CardRank'
我假设这是因为它需要一个完整的类型并且 CardRank.Number
没有指定一个完整的类型,而 CardRank.Number(2)
做了.但是,在这种情况下,我希望它匹配任何数字;不只是一个特定的.
I'm assuming this is because it's expecting a full type and CardRank.Number
does not specify an entire type, whereas CardRank.Number(2)
did. However, in this case, I want it to match any number; not just a specific one.
显然我可以使用 switch 语句,但实现 ==
运算符的全部目的是避免这种冗长的解决方案:
Obviously I can use a switch statement, but the whole point of implementing the ==
operator was to avoid this verbose solution:
switch number {
case .Number:
print("You must play a face card!")
default:
break
}
有什么方法可以将枚举与关联值进行比较而忽略其关联值?
Is there any way to compare an enum with associated values while ignoring its associated value?
注意:我意识到我可以将 ==
方法中的 case 更改为 case (.Number, .Number): return true
,但是,虽然它会正确返回 true,但我的比较看起来仍然像是在与特定数字进行比较(number == CardRank.Number(2)
; 其中 2 是一个虚拟值)而不是比任何数字(number == CardRank.Number
).
Note: I realize that I could change the case in the ==
method to case (.Number, .Number): return true
, but, although it would return true correctly, my comparison would still look like its being compared to a specific number (number == CardRank.Number(2)
; where 2 is a dummy value) rather than any number (number == CardRank.Number
).
正如 Etan 指出的,你可以省略 (_)
通配符匹配来使用这个更干净.
As Etan points out, you can omit the (_)
wildcard match to use this more cleanly.
不幸的是,我认为没有比 Swift 1.2 中的 switch
方法更简单的方法了.
Unfortunately, I don't believe that there's an easier way than your switch
approach in Swift 1.2.
然而,在 Swift 2 中,您可以使用新的 if-case
模式匹配:
In Swift 2, however, you can use the new if-case
pattern match:
let number = CardRank.Number(5)
if case .Number(_) = number {
// Is a number
} else {
// Something else
}
如果您想避免冗长,您可以考虑将 isNumber
计算属性添加到实现 switch 语句的枚举中.
If you're looking to avoid verbosity, you might consider adding an isNumber
computed property to your enum that implements your switch statement.