-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
1
  • condition1 || condition4 || condition7 ? return 1 : ( condition2 || condition5 ? return 2: return 3); Commented Feb 25, 2013 at 21:44

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I showed a block based approach here: stackoverflow.com/questions/104339/…
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!
0
if ( condition1 ) return 1;
else if ( condition 2 ) return 2;
else if ( condition 3 ) return 1;
.....

1 Comment

thanks. sorry for being stupid.
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;
}

Comments

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");
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.