4

I often encounter the following kind of situation in Swift code:

if x == A || x == B {
    // do something
}

Is there any way to shorten it?

pkamb
  • 33,281
  • 23
  • 160
  • 191

3 Answers3

8

I like switch statements for cases like this

switch x {
    case A, B, C:
        // do stuff
    case D:
       // other stuff
    default:
      // do default stuff
}
hooliooo
  • 528
  • 1
  • 5
  • 13
2

Use Array instead, if all values of same type. if you just want to check x is matching to any values.

for example:

let x = 10
let A = 20
let B = 40
let C = 40


let myArray = [A, B,C]


if myArray.contains(x) {
  // do something
}
Sahil
  • 9,096
  • 3
  • 25
  • 29
0
if (x ^ A) * (x ^ B) * (x ^ C) == 0 {
    //do what you need
}

Shorter? Not sure... More impressive? Definitely.

Max Pevsner
  • 4,098
  • 2
  • 18
  • 32
  • `|` would be faster than `*` – Alexander Dec 01 '16 at 07:47
  • 1
    Will only work if `x`, `A`, `B`, `C` are conforming to `BitwiseOperations` protocol (if `^` and `|` is used), and for `*` you need extra protocol conformance. And to compare it with `0` you also need to define `==` with left operand being `x`'s type, and right being `Int`. So that solution only works on really small subset of types, or if `x` is some kind of `Int`, and it may not be. – user28434'mstep Dec 01 '16 at 07:54
  • Also it does not short-circuit as the `||` operator does. – Martin R Dec 01 '16 at 07:55