-3

How would I approach the following in Objective-c?

I want to construct a method that tests several conditions. Below some pseudo code to express what I want to achieve:

if
   condition1 fulfilled, return 1
   condition2 fulfilled, return 2
   condition3 fulfilled, return 1
   condition4 fulfilled, return 1
   condition5 fulfilled, return 2
   no condition fulfilled, return 3 
end if
Sjakelien
  • 2,255
  • 3
  • 25
  • 43

4 Answers4

2

Several considerations may apply, depending on whether the conditions are mutually exclusive or not.

If the conditions are mutually exclusive, the simplest solution is to group them by their return value:

if (condition1 || condition3 || condition4) return 1;
if (condition2 || condition5) return 2;
return 3;

If the conditions are not mutually exclusive, you can group together only the ones that are next to each other in the testing order:

if (condition1) return 1;
if (condition2) return 2;
if (condition3 || condition4) return 1;
if (condition5) return 2;
return 3;

Note that although you do not need an else after a return, it is common in some shops to include an else anyway. This is a matter of coding standardization which should be decided together by your coding team.

If you would like to get really fancy, you can create an array of blocks, test conditions in order, and return the value returned by the block. This is by far the trickiest approach. It would significantly impair readability, unless the conditions are structured in the same way, and the code makes sense to the reader. Chains of ifs always make sense to a reader, so it is very hard to compete on readability with them.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • I showed a block based approach here: http://stackoverflow.com/questions/104339/objective-c-switch-using-objects/14789501#14789501 – vikingosegundo Feb 25 '13 at 21:54
  • This one suits my needs much better. I like the syntax. It's pretty clean, but not really according to the nested/indented brackets I'm used to. Thanks! – Sjakelien Feb 25 '13 at 22:55
0
if ( condition1 ) return 1;
else if ( condition 2 ) return 2;
else if ( condition 3 ) return 1;
.....
Dan F
  • 17,654
  • 5
  • 72
  • 110
0

You'd approach this exactly the same way as in any C-like language:

if (condition1) {
    return 1;
} else if (condition2) {
    return 2;
} else if ...

} else {
    return 3;
}
puzzle
  • 6,071
  • 1
  • 25
  • 30
0

You got nice answers, but if you only want to compare two single values:

int variableToCompare = ...;
switch (variableToCompare) {
     case 1: NSLog(@"1"); break;
     case 2: NSLog(@"2"); break;
     case 3: NSLog(@"3"); break;
     default: NSLog(@"This will be executed if any of the conditions above are YES");
};
Lluís
  • 578
  • 1
  • 5
  • 10