3

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)

Dietrich
  • 123
  • 1
  • 6
  • 2
    Closely related: [How to test equality of Swift enums with associated values](http://stackoverflow.com/questions/24339807/how-to-test-equality-of-swift-enums-with-associated-values) – Hamish Dec 10 '16 at 23:17
  • @Hamish, thanks for finding an apropos question-and-answer! Apologies to all for missing it. – Dietrich Dec 10 '16 at 23:32
  • What's the stackoverflow protocol here?... @Hamish pointed out a previous answered question that directly addresses my question—should I answer my own question to point that fact out, leave it for someone else to make that an answer, or do nothing? – Dietrich Dec 10 '16 at 23:38
  • Well Martin's answer is also a good solution to the problem. Given that the other Q&A is more specific about requiring the comparison to be a boolean expression, whereas your question is just about how to make the comparison with a guard, which Martin's answer covers, I would suggest leaving it as-is. – Hamish Dec 10 '16 at 23:50
  • Note that `case strange(charge)` doesn't compile – you need to give `charge` a type. – Hamish Dec 10 '16 at 23:52
  • Yes, that was a bit of 'lorem ipsum' there. Just thinking of how quarks have a charge property. – Dietrich Dec 11 '16 at 01:36

0 Answers0