阅读
How to test equality of Swift enums with associated values后,我实现了以下枚举:
原文链接:https://www.f2er.com/swift/320732.htmlenum 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!") }
…它给出以下错误信息:
Binary operator ‘==’ cannot be applied to operands of type ‘CardRank’ and ‘(Int) -> CardRank’
我假设这是因为它期待一个完整的类型,CardRank.Number不指定整个类型,而CardRank.Number(2)。但是,在这种情况下,我想要匹配任何数字;不只是一个具体的。
显然我可以使用switch语句,但是实现==操作符的全部要点是避免这种详细的解决方案:
switch number { case .Number: print("You must play a face card!") default: break }
有没有办法将枚举与关联值进行比较,而忽略其关联值?
注意:我意识到我可以将==方法中的case更改为case(.Number,.Number):return true,但是尽管它将正确返回true,但我的比较仍将看起来像是与特定数字进行比较(number == CardRank.Number(2);其中2是虚拟值),而不是任何数字(number == CardRank.Number)。