Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 15 / 68

The ternary operator

This lesson covers Objective-C's ternary operator, with the aim of expressing a branch concisely on one line.

condition ? value_if_true : value_if_false expresses a simple if statement on one line. It suits short branches such as deciding a message from whether someone is an adult.

The sample code assigns an age-dependent message to message in the single line age >= 20 ? @"Adult" : @"Minor". Note the @ in front of each string object.

A common early stumble is overusing it until the code becomes hard to read. Cramming a complicated condition in makes things worse, so keep it for simple two-way choices.

In professional work, the ternary operator is used for straightforward assignments and for picking between two messages.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)