简体   繁体   中英

What is the ?: operator

In an example of Objective-C code I found this operator

self.itemViews[@(0)] ?: [self.dataSource slidingViewStack:self viewForItemAtIndex:0 reusingView:[self dequeueItemView]];

The code does compile under Apple LLVM 4.2.

The only thing I came across was in being a vector operator, but I don't think Objective-C, and for that matter C, has vector operators. So can someone please give reference and or documentation of this operator.

?: is the C conditional operator .

a ? b : c

yields b value if a is different than 0 and c if a is equal to 0 .

A GNU extension ( Conditional with Omitted Operand ) allows to use it with no second operand:

 x ? : y 

is equivalent to

 x ? x : y

Are you familiar with the Ternary operator ? Usually seen in the style:

test ? result_a : result_b;

All that has happened here is that the first branch has not been given so nothing will happen in the positive case. Similar to the following:

test ?: result_b;

Due to the way that C is evaluated, this will return result_b if test is untruthy, otherwise it will return test .

In the example that you have given - if the view is missing, it falls back to checking the datasource to provide a replacement value.

The above is called Ternary operator or conditional operator.

Syntax is,

     <condition>?<true_part>:<false_part>

Here if condition is true, will be considered as value else will be considered as value.

Please refer this, http://en.wikipedia.org/wiki/%3F:

It is the ternary operator , as Objective-C is a superset of C you can use this operator.

Some tutorial on this.

a = x ? : y;

The expression is equivalent to

a = x ? x : y;

It is the ? operator, called ternary operator, which is used in this way:

condition ? true-branch : false-branch; 

When condition evaluates to true (non zero), the branch before the : is executed, otherwise the other branch is executed. This may even return a value:

value = condition ? true-branch : false-branch; 

In your case the return value is ommited and the true-branch is empty (nothing to do). The return value of condition is returned then but not used in your example.

Equivalent of

if (!self.itemViews[@(0)]) 
  [self.dataSource slidingViewStack:self viewForItemAtIndex:0 reusingView:[self dequeueItemView]];

which is imho much better programming style.

此运算符在Objective C中使用 ,此运算符用于条件运算符。是运行一个语句还是其他语句取决于所使用的逻辑术语和您提供的输入。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM