0

I am learning Objective C for ios programming and ran into the following line of code in the getter method of a property of a card called suit:

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

This is supposed to return "?" if the suit is nil but I'm not sure how this line works. What does the ? in "return _suit ?..." mean? How does this code function and how is it interpreted by the computer?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
darora
  • 9
  • 1
  • 2

3 Answers3

1

That's the ternary operator. You can search the site to find out more.

Basically it means "if".

If _suit is not nil, return _suit, otherwise return @"?". (the "otherwise" is after the colon).

nevan king
  • 112,709
  • 45
  • 203
  • 241
0

It it s ternary operator it is a short form of

if(_suit) {
   return _suit;
} else {
   return @"?";
}
Matthew Graves
  • 3,226
  • 1
  • 17
  • 20
  • Just to be clear: The ternary operator does not cause the function to return. It's only equivalent to that when used in a return statement. – Chuck Jun 25 '13 at 18:51
  • I'm aware of that, I was restating the expression: return _suit ? _suit: @"?"; – Matthew Graves Jun 25 '13 at 22:06
0

? Is ternary operator which work very similar to if()...else...

(condition)?<value if true>:<value if false>

Read following:

Objective-C Tricks: #1 Ternary Operations
Objective-C ternary operator

CRDave
  • 9,279
  • 5
  • 41
  • 59