How to compare enum with associated values by ignoring its associated value in Swift? -
after reading how test equality of swift enums associated values, implemented 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)) == 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 } }
the following code works:
let card: cardrank = cardrank.jack if card == cardrank.jack { print("you played jack!") } else if card == cardrank.number(2) { print("a 2 cannot played @ time.") }
however, doesn't compile:
let number = cardrank.number(5) if number == cardrank.number { print("you must play face card!") }
... , gives following error message:
binary operator '==' cannot applied operands of type 'cardrank' , '(int) -> cardrank'
i'm assuming because it's expecting full type , cardrank.number
not specify entire type, whereas cardrank.number(2)
did. however, in case, want match any number; not specific one.
obviously can use switch statement, whole point of implementing ==
operator avoid verbose solution:
switch number { case .number: print("you must play face card!") default: break }
is there way compare enum associated values while ignoring associated value?
note: realize change case in ==
method case (.number, .number): return true
, but, although return true correctly, comparison still being compared specific number (number == cardrank.number(2)
; 2 dummy value) rather any number (number == cardrank.number
).
edit: etan points out, can omit (_)
wildcard match use more cleanly.
unfortunately, don't believe there's easier way switch
approach in swift 1.2.
in swift 2, however, can use new if-case
pattern match:
let number = cardrank.number(5) if case .number(_) = number { // number } else { // else }
if you're looking avoid verbosity, might consider adding isnumber
computed property enum implements switch statement.
Comments
Post a Comment