0

Say we have an enum:

enum MyEnum {
  case foo(Int)
  case bar
}

and we can do something like this:

func myFunc(_ foo: MyEnum, _ bar: MyEnum) {
  if case .foo(_) = foo, case .bar = bar {...}
}

but what if I need some like this

if case .foo(_) = foo, case .bar = bar OR someVar == true {...}

where I want either case .foo(_) = foo, case .bar = bar to be true, or someVar to be true.

Apparently I can't put || there, and I couldn't figure out an alternative. Am I missing something simple?

Stephenye
  • 806
  • 6
  • 12
  • so, in your thinking... what are the _left_ and _right_ arguments of the `||` (OR) operand here? – holex Feb 19 '18 at 16:52
  • 2
    Possible duplicate of [Is it possible to abbreviate this condition in Swift?](https://stackoverflow.com/questions/48706702/is-it-possible-to-abbreviate-this-condition-in-swift) – Dávid Pásztor Feb 19 '18 at 16:55
  • @holex: I edited the question to be more specific – Stephenye Feb 19 '18 at 16:56
  • @Dávid Pásztor, I disagree it is a duplicate of the question you pointed out. I am not trying to abbreviating anything, and I still couldn't think of a way of doing the OR after reading that question. – Stephenye Feb 19 '18 at 17:01
  • @holex: you made me thinking, what if I want either `case .foo(_) = foo` to be true, or `case .bar = bar OR someVar == true` to be true? – Stephenye Feb 19 '18 at 17:04

1 Answers1

2

I'm not sure if this is possible with a single if statement. However, you could use a switch statement like this:

enum MyEnum {
    case foo(Int)
    case bar
}

func myFunc(_ foo: MyEnum, _ bar: MyEnum, _ someVar: Bool) {
    switch (foo, bar, someVar) {
    case (.foo, .bar, _), (_, _, true):
        break
    default:
        break
    }
}
tonisuter
  • 789
  • 5
  • 13
  • thanks @tonisuter, that would work. But it's a bit odd to not be able to use a `if` statement in such case. – Stephenye Feb 19 '18 at 18:04