-1

everyone,

I am new to C / Objective-C and I am doing some exercise in Xcode. Actually it was lecture two from Stanford iTunes.U CS 193 iOS course fall 2013, if somebody's familiar with...

The exercise was asking to create a property for a class called Card.

So in .h file it declares:

@property (strong, nonatomic) NSString *suit;

And in .m file it overrode the getter method:

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

Here it is, I don't understand what this return statement means...

According to the instructor, the getter method prevents the suit property being nil. But I tried to use the following code instead of the code above, it didn't work.

-(NSString *)suit
{
    if (!_suit)
        return _suit;
    else
        return @"?";
}

So two questions here:

1,

return _suit ? _suit : @"?";

what does this return statement mean?

2, Why my code did not work?

Appreciated!

bing
  • 450
  • 3
  • 6
  • 15

2 Answers2

2

The x ? y : z syntax is called the conditional or ternary if operator. If x is true, its value is y, otherwise its value is z.

When you converted it into the if/else form, you inverted _suit, when you shouldn't have. It should read:

if (_suit)
    return _suit;
...
Xymostech
  • 9,710
  • 3
  • 34
  • 44
  • It is called *conditional* operator. – Martin R Nov 27 '13 at 06:19
  • That was clear. Thanks a million! – bing Nov 27 '13 at 06:22
  • @MartinR Since it's the only ternary operator in C, I usually just hear it called the ternary operator. I don't think I've ever actually heard it called by something useful like the conditional operator, but that does make more sense. – Xymostech Nov 27 '13 at 06:22
1

change your code to as followings:

-(NSString *)suit
{
    if (_suit) //if _suit exists, then return _suit. !_suit is wrong.
        return _suit;
    else
        return @"?";
}
chancyWu
  • 14,073
  • 11
  • 62
  • 81