Stephenye
Stephenye

Reputation: 814

Swift if case with logical OR

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?

Upvotes: 0

Views: 570

Answers (1)

tonisuter
tonisuter

Reputation: 859

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
    }
}

Upvotes: 2

Related Questions