ios - C/Objective C 中奇怪的 return 语句

标签 ios objective-c c return

大家

我是 C/Objective-C 新手,正在 Xcode 中做一些练习。实际上,这是 2013 年秋季斯坦福大学 iTunes.U CS 193 iOS 类(class)的第二讲,如果有人熟悉的话……

该练习要求为名为 Card 的类创建一个属性。

因此在 .h 文件中声明:

@property (strong, nonatomic) NSString *suit;

并且在 .m 文件中它覆盖了 getter 方法:

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

就是这样,我不明白这个 return 语句是什么意思...

根据讲师的说法,getter 方法可以防止西装属性为零。但我尝试使用下面的代码代替上面的代码,但没有成功。

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

这里有两个问题:

1,

return _suit ? _suit : @"?";

这个返回语句是什么意思?

2、为什么我的代码不起作用?

感谢!

最佳答案

x ? y : z 语法称为 conditional or ternary if operator 。如果x为真,则其值为y,否则其值为z

当您将其转换为 if/else 形式时,您颠倒了 _suit,而您不应该这样做。它应该是:

if (_suit)
    return _suit;
...

关于ios - C/Objective C 中奇怪的 return 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20235192/

相关文章:

iphone - 提交证书签名申请批准

ios - 如何在 Windows 上激活 ios.windows xamarin

objective-c - Objective - C,使用 NSDecimalNumberHandler 和 NSDecimalNumberBehaviors 协议(protocol)

ios - 'UILabel ?' does not have a member named ' 文本'

ios - 更改 UIWebView 上的 cookie 策略

objective-c - 我应该释放我创建的NSThread吗?

iphone - 旋转/幸运轮

CUDA 驱动程序 API 等效于 cudaSetDevice

c - 将 Torvalds 的 "Good Taste"应用于 Fortran 链表

c++ - VS2010 中的 Windows 窗体应用程序无需 .NET?