swift - Compiler error when comparing values of enum type with associated values? -


class myclass  {     enum myenum {         case firstcase         case secondcase(int)         case thirdcase     }      var state:myenum!      func mymethod ()     {         if state! == myenum.firstcase {             //         }     } } 

i compiler error pointing @ if statement::

binary operator '==' cannot applied 2 'myclass.myenum' operands

if instead, use switch statement, there no problem:

switch state! {     // also, why need `!` if state      // implicitly unwrapped optional? because optionals      // internally enums, , compiler gets confused?  case .firstcase:     // something...  default:     // (do nothing)     break } 

however, switch statement feels verbose: want do something .firstcase, , nothing otherwise. if statement makes more sense.

what's going on enums , == ?

edit: ultra-weird. after settling switch version , moving on other (totally unrelated) parts of code, , coming back, if-statement version (comnparing force-unwrapped property against fixed enum case) compiling no errors. can conclude has corrupted cache in parser got cleared along way.

edit 2 (thanks @leodabus , @martinr): seems error appears when set associated value other enum case (not 1 comparing against - in case, .secondcase). still don't understand why triggers compiler error in particular ("can't use binary operator '=='..."), or means.

as said in comment, enumeration type has associated values. in case there no default == operator enum type.

but can use pattern matching in if statement (since swift 2):

class myclass {     enum myenum {         case firstcase         case secondcase         case thirdcase(int)     }      var state:myenum!      func mymethod () {         if case .firstcase? = state {          }     } } 

here .firstcase? shortcut .some(myenum.firstcase).

in switch-statement, state not automatically unwrapped, if implicitly unwrapped optional (otherwise not match against nil). same pattern can used here:

switch state { case .firstcase?:     // something... default:     break } 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -