Preamble: I understand that a practical work-around to my question is to use a full switch
statement. I'm mainly asking to see if I'm misunderstanding Swift here.
Given an enum
, for example:
enum Quark1 {
case charm
case strange
// ...
}
A guard
statement like below, which is how I'd like the code I'm writing to read, works fine:
guard someQuark != .charm else { // ... }
However, if one (or more, but not all) cases of my enum have associated data, like this:
enum Quark2 {
case charm
case strange(charge)
// ...
}
Then the same 'guard case' statement...
guard someQuark != .charm else { // no bueno
...gets this error message:
Binary operator '!=' cannot be applied to operands of type 'Quark' and '_'
Is there a way to test for an enum case—without associated data, from an enum where other cases do have associated data—in a one line conditional, like if
and guard
?
Yes, a switch
statement will get the job done. This is more a theory question than a practical problem.
p.s. Apologies to physicists, I realize these examples are not standard (hah!) models of real quarks.
(edited to highlight the crucial points)