Reputation: 4652
Is there any short syntax for if-else statement in objective C like PHP:
if($value)
return 1;
else
return 0;
shorter version:
return $value?1:0;
Upvotes: 34
Views: 41350
Reputation: 35626
Yes.
There is the Conditional (Ternary) Operator
.
Example (pseudo):
value = (expression) ? (if true) : (if false);
Based on your example (valid code):
int result = value ? 1 : 0;
Upvotes: 114
Reputation: 2364
Surprised that nobody has suggested the following :
Long version :
if(value)
return 1;
else
return 0;
Small version :
return value;
And if value
isn't a bool
variable, just cast it : return (BOOL)value;
Upvotes: 1
Reputation: 723598
It's exactly the same in both languages, except you typically don't find $
signs in Objective-C variable names.
if(value)
return 1;
else
return 0;
return value?1:0;
You should also keep in mind that the conditional operator ?:
isn't a shorthand for an if-else statement so much as a shorthand for a true vs false expression. See the PHP manual.
Upvotes: 13