Faryar Fathi

Composer, Coder, Entrepreneur

Quick Tip: Objective-C Ternary Operator

Use conditional operators (aka ternary operators) to make your code more legible and clear. Conditional assignment is the most common use case for ternary operators.

With the ternary operator, you can turn this:

1
2
3
4
5
6
7
int days;

if (thisYear == leapYear) {
  days = 366;
} else {
  days = 365;
}

into this:

1
int days = (thisYear == leapYear) ? 366 : 365;

Only one line of code, and a lot easier to read and understand when you’re familiar with the syntax.

Syntax

The basic syntax for using the ternary operator is:

1
condition ? value_if_true : value_if_false

As you can see, ternary operator checks the condition and returns one of the values based on the result.

Bonus Tip:

In some cases, you can even omit the true side of operation. Consider the following statement:

1
UIImage *profilePhoto = self.uploadedPhoto ? self.uploadedPhoto : defaultPhoto;

Here, we check to see if our user has uploaded a profile photo. If that’s the case, self.uploadedPhoto is non-nil and will evaluate to TRUE. Consequently, self.uploadedPhoto will be returned and assigned to profilePhoto. However if no photo has been uploaded, self.uploadedPhoto will be nil and will evaluate to FALSE. Therefore, defaultPhoto will be assigned to profilePhoto.

The above statement can be rewritten like this:

1
UIImage *profilePhoto = self.uploadedPhoto ? : defaultPhoto;

Again, if self.uploadedPhoto is non-nil, it will be assigned to profilePhoto, otherwise, defaultPhoto will.