Firdous
Firdous

Reputation: 4652

Short IF ELSE syntax in objective C

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

Answers (3)

Alladinian
Alladinian

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

Jonathan F.
Jonathan F.

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

BoltClock
BoltClock

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

Related Questions