Search code examples
objective-cif-statementconditional-statementsconditional-operatorinline-if

Is there any difference between '?:' and an if statement in objective c?


Is there a difference between using the '?:' conditional and the simple 'if-then-else' statement? Is it simply another way to do it, or does it actually use less space/take less time to read than 'if' statements?

Example:

If statement:

if (item1.isEqualToString:@"2") //If statement
    [self doSomething];
else
    [self doSomethingElse];

item1.isEqualToString:@"2" ? [self doSomething] : [self doSomethingElse]; //'?:' statement

Solution

  • Yes, there is a difference.

    Semantically an if/else statement means

    if (condition)
      statements
    else
      statements
    

    while a the ternary conditional is

    condition ? expression : expression
    

    so you can assign the result of a ?: operator to something while you can't do it with an if statement. Actually the ?: operator is an expression itself so you can nest it inside other expressions, even other ?: operators.

    The ?: is also type checked, this

    condition ? [self methodThatReturnsVoid] : [self methodThatReturnsInt]
    

    raises an error since the result type could change according to condition.