mhergon
mhergon

Reputation: 1678

"if-else" with multiple OR / Objective-C

I have a question and I have not been able to find an answer. Is there any way to reduce the following expression in Objective-C?

if ((r != 1) && (r != 5) && (r != 7) && (r != 12)) {
   // The condition is satisfied
}else{
   // The condition isn't satisfied
}

For example (not working):

if (r != (1 || 5 || 7 || 12)) {
   // The condition is satisfied
}else{
   // The condition isn't satisfied
}

Thanks!

Upvotes: 2

Views: 805

Answers (2)

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39978

You can also use switch for this like

switch (r)
{
    case 1:
    case 5:
    case 7:
    case 12:
        // r is having 1,5,7 or 12
        break;
    default:
        // r is having other values
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You can use NSSet, like this:

NSSet *prohibited = [NSSet setWithArray:@[@1, @5, @7, @12]];
if (![prohibited containsObject:[NSNumber numberWithInt:r]]) {
    // The condition is satisfied
} else {
    // The condition isn't satisfied
}

If the set of numbers contains a fixed group of numbers, such as in your example, you can make the NSSet *prohobited a static variable, and initialize it once, rather than doing it every time as in my example above.

Upvotes: 4

Related Questions