Wednesday, February 3, 2016

Objective C Conditional Operator (x ? y : z)

In any programming language we go with writing bunch of ifs else ifs and else statement if there are bunch of conditions in a scenario.

         else if(case1){


In these situations we can go with a switch statement also. 

        switch (country)
            case India:

            case USA:

            case China:     


But, what if we have only two conditions for a scenario like shown below.

We have an integer variable.

int val = 10;

I just want to check whether it is an even one or an odd one. To check this we can go for if statements also as shown below.

if(val %2 == 0){

               // Even number


               // Odd number

Instead of above style, We can use conditional operator to make it a single line as shown below.

BOOL even = (val %2 == 0) ? YES : NO

If the condition is success, even will have YES value. If not a NO value.

In these cases, this operator is simple and handy and readable. Isn't it?

Hope this post is useful. Feel free to comment in case of any queries.