【问题标题】:Ternary operator assignment in Objective-C [duplicate]Objective-C中的三元运算符赋值[重复]
【发布时间】:2013-08-13 23:04:15
【问题描述】:

我找到了一种分配值的方法,如下所示:

NSString *result = [self string] ?: @"none";

如果[self string] 返回一个不等于 nil 的值,则结果将是该返回值,否则为 @"none"。就像 Python 中的 or 运算符。

我测试了几个案例,效果很好。喜欢:

int a = 10 ?: 0; // a is 10
int a = 0 ?: 5; // a is 5
NSString *str = @"abc" ?: 10; // warning: incompatible pointer. It has type checking?

但我找不到任何有关此语法的相关文档或信息。所以我想知道为什么它有效。谁能解释一下?

【问题讨论】:

    标签: objective-c ternary-operator


    【解决方案1】:

    这是 C 的 GNU 扩展,记录在 here。请注意,它只对表达式求值一次,并重用结果(当您的表达式有副作用时很有用)。 clang 包含它,但我找不到任何相关文档。


    编辑:这是使用 LLVM 实现的类参考:http://clang.llvm.org/doxygen/classclang_1_1BinaryConditionalOperator.html

    注意是说:

    BinaryConditionalOperator - 条件运算符的 GNU 扩展,允许省略中间操作数。

    【讨论】:

    • 完全明白。非常感谢。
    猜你喜欢
    • 2011-03-06
    • 2021-04-29
    • 2019-05-24
    • 2013-06-28
    • 2012-04-06
    • 2021-11-23
    • 2012-11-07
    • 2021-04-19
    • 2011-07-02
    相关资源
    最近更新 更多