3

How would you write this:

if case .SomeEnum(3) = enumType where myInt == 3 {
   //I don't need this case
} else {
   //This is the case I need
}

I know I could use guard:

guard case .SomeEnum(3) = enumType where myInt == 3 else {
    //This is the case I need
}

but I don't think it is clean, since it is not really a case in which the function is not able to finish. Also, guard expects me to return from the function.

Any other alternatives?

Daniel
  • 20,420
  • 10
  • 92
  • 149
  • Couldn't it just be `if .SomeEnum != enumType || myInt != 3`? – Alexander Jun 20 '16 at 15:43
  • `.SomeEnum != enumType` or `.SomeEnum == enumType` gives compiler errors, since the enums have parameters – Daniel Jun 20 '16 at 15:44
  • Oh I see. Good question :) – Alexander Jun 20 '16 at 15:50
  • 2
    To the best of my knowledge, you *cannot* negate a pattern. I would consider your first solution as the best one, alternatively a switch statement with one case plus the `default` case. – You *can* use guard with a local scope, but that would be more like obfuscating Swift. – Martin R Jun 20 '16 at 16:06

1 Answers1

3

You cannot negate a pattern (as far as I know), and your first solution using if/else looks fine to me, the intention of the code is clearly visible.

A switch statement would be an alternative:

switch enumType {
case .SomeEnum(3) where myInt == 3:
    break  // I don't need this case
default:
    // This is the case I need
    // ...
}

With regard to your remark

Also, guard expects me to return from the function.

that is not entirely true. You are expected to leave the current scope. So this would compile and work as expected:

repeat {
    guard case .SomeEnum(3) = enumType where myInt == 3 else {
        // This is the case I need
        // ...
        break
    }
} while false

but I would not consider that a better solution.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • I had the same idea using `switch`, the *don't need* pattern is `case .SomeEnum(let value) where value == 3 && value == myInt:` or maybe even simply `case .SomeEnum(let value) where value == myInt:` – vadian Jun 20 '16 at 16:34
  • @vadian: `case .SomeEnum(3) where myInt == 3:` would be the same pattern as in the question. – Martin R Jun 20 '16 at 16:39
  • @vadian: `case .SomeEnum(let value) where value == myInt:` (if that is what OP actually meant) can be shortened to `case .SomeEnum(myInt):` – Martin R Jun 20 '16 at 16:41
  • 1
    You can use `do { ... }` instead of `repeat { ... } while false`. – NobodyNada Jun 20 '16 at 17:57
  • @NobodyNada: Yes, but – unless I am overlooking something – you can break out of it only if you give it a label: `LABEL: do { ... }` and `break LABEL`. – Martin R Jun 20 '16 at 19:08