swift - Can I use the pattern matching operator ~= to match an enum value to an enum type with an associated variable? -
this question has answer here:
i compare enum value enum type without using switch. following code, example, works using ~=
operator:
enum myenum { case a, b } let myenum = myenum.a let isa = myenum ~= myenum.a
isa
equals true
above.
however, when try compare enum of enum type associated value, below, compile error binary operator '~=' cannot applied 2 myenum operands
.
enum myenum { case a, b(object: any) } let myenum = myenum.a let isa = myenum ~= myenum.a
is there way work around error use ~=
pattern matching operator? or recourse following syntax, in opinion more cumbersome:
enum myenum { case a, b(object: any) } let myenum = myenum.a let isa: bool switch myenum { case .a: isa = true default: isa = false }
thanks in advance input , suggestions!
from documentation swift 1.2 "enumeration case patterns appear in switch
statement case labels". yes, need define ~=
operator (as answer pointed in comments).
in case need isa
, isb
can implement them using switch
combined _
. in case ~=
couldn't work out of box anyway, since use any
associated type, not equatable
(i.e.: how can if 2 .b(any)
equal since cannot if 2 equal?)
as example, here implementation of code uses string
associated type. in case need isa
, isb
, can still use any
associated type without implementing ~=
operator.
enum myenum { case a, b(object: string) } let myenuma = myenum.a let myenumb = myenum.b(object: "foo") func ~=(lhs: myenum, rhs: myenum) -> bool { switch (lhs, rhs) { case (.a, .a): return true case let (.b(left), .b(right)): return left == right default: return false } } myenuma ~= .a // true myenumb ~= .b(object: "foo") // true myenumb ~= .b(object: "bar") // false func isa(value: myenum) -> bool { switch value { case .a: return true default: return false } } func isb(value: myenum) -> bool { switch value { case .b(_): // ignore associated value return true default: return false } }
Comments
Post a Comment