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?
I like switch statements for cases like this
switch x {
case A, B, C:
// do stuff
case D:
// other stuff
default:
// do default stuff
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With