NebulaFox
NebulaFox

Reputation: 8323

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.

Upvotes: 10

Views: 8583

Answers (6)

Sahana
Sahana

Reputation: 587

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:

Upvotes: 3

Dorothy Estes
Dorothy Estes

Reputation: 35

This operator is used in Objective C and this operator is used for conditional operator.Whether one statement will be run or while other it depends upon the logical term that is used and the input you are providing.

Upvotes: 1

Aaron Cronin
Aaron Cronin

Reputation: 2103

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.

Upvotes: 5

Hermann Klecker
Hermann Klecker

Reputation: 14068

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.

Upvotes: 1

ouah
ouah

Reputation: 145899

?: 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

Upvotes: 18

AllTooSir
AllTooSir

Reputation: 49432

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;

Upvotes: 1

Related Questions