Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I say “if x == A or B or C” as succinctly in Swift as possible? [duplicate]

Tags:

swift

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?

like image 656
Barış Özçelik Avatar asked Dec 23 '22 23:12

Barış Özçelik


2 Answers

I like switch statements for cases like this

switch x {
    case A, B, C:
        // do stuff
    case D:
       // other stuff
    default:
      // do default stuff
}
like image 108
hooliooo Avatar answered Jun 06 '23 07:06

hooliooo


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
}
like image 24
Sahil Avatar answered Jun 06 '23 07:06

Sahil