如何通过在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:
二进制运算符'=='不能应用于o CardRank和(Int) - > CardRank'的类型
Binary operator '==' cannot be applied to operands of type 'CardRank' and '(Int) -> CardRank'
我假设这是因为它期待一个完整的类型而$ code> CardRank.Number 没有指定整个类型,而$ code> 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(.Number,.Number):return 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中有一个比开关
方法更容易的方法。
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.