0

Possible Duplicate:
What does the question mark and the colon (?: ternary operator) mean in objective-c?

I understand that we're setting oldRow equal to some index path. I have never seen this syntax and can't find explanation in the book I'm using. What is the purpose of the ? in the code below and what exactly does this code do?

int oldRow = (lastIndexPath != nil) ? [lastIndexPath row] : -1;
Community
  • 1
  • 1
Sean Smyth
  • 1,349
  • 3
  • 23
  • 42

3 Answers3

7
int oldRow = (lastIndexPath != nil) ? [lastIndexPath row] : -1;

is equivalent to:

int oldrow = 0;
if (lastIndexPath != nil)
    oldRow = [lastIndexPath row];
else 
    oldRow = -1;

That syntax is called a ternary operator and follows this syntax:

condition ? trueValue : falseValue;

i.e oldRow = (if lastIndexPath is not nil ? do this : if it isn't do this);
max_
  • 23,337
  • 38
  • 120
  • 209
2

This is a shorthand if statement. Basically it is the same as:

int oldRow;

if(lastIndexPath != nil)
{
    oldRow = [lastIndexPath row];
}
else
{
     oldRow = -1;
}

It is very handy with conditional assignments

rooster117
  • 5,472
  • 1
  • 19
  • 19
1

this code is equal to this code

int oldRow;

if (lastIndexPath != nil)
   oldRow = [lastIndexPaht row];
else
   oldRow = -1;
Omar Abdelhafith
  • 21,143
  • 5
  • 51
  • 55