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,509
  • 3
  • 25
  • 43

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_
  • 24,076
  • 39
  • 122
  • 211
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,502
  • 1
  • 21
  • 19
1

this code is equal to this code

int oldRow;

if (lastIndexPath != nil)
   oldRow = [lastIndexPaht row];
else
   oldRow = -1;
Omar Abdelhafith
  • 21,163
  • 5
  • 52
  • 56