-1

Can someone please help to explain the syntax of the following code for me? It meant to "return ? if _suit is nil, and return a corresponding string in an array if _suit is not nil".

- (NSString *)suit
{
    return _suit ? _suit : @"?";
}

Is it equivalent to the following code?

if (!_suit) {
    return @"?";
} else {
    return ?
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044

2 Answers2

3

Yes, this is a shortening of an if block. It is a conditional operator.

The format is as follows (same in many other languages):

condition ? ifTrue: ifFalse; 

So your code:

return _suit ? _suit : @"?";

Is the same as

if(_suit) {
    return _suit;
} else {
    return @"?";
}

You can read more about it here.

Alex K
  • 8,269
  • 9
  • 39
  • 57
2

No it is not the same. The '?:' operator describes following it is just an if else statement as one-liner:

(if clause) ? : .

so in your case that would mean:

if (!_suit) {
   return @"?";
} else {
   return _suit;
}
hasan
  • 553
  • 1
  • 5
  • 19