Ad space (banner)
๐ŸฆSwift Lessons
Lesson 15 / 68

The Ternary Operator

In this lesson you will learn how to use the ternary operator in Swift to express a branch concisely on a single line. This is for anyone searching for "Swift ternary operator how to use".

condition ? valueIfTrue : valueIfFalse expresses a simple if statement on one line. It is handy when a short branch does not deserve a full if statement.

The sample code assigns a message to message based on age with the single line age >= 20 ? "Adult" : "Minor". Its biggest advantage is compressing something that would take several lines with an if statement into one.

A common stumbling block for beginners is over-using it until the code becomes harder to read. Cramming a complex condition in makes things worse, so the trick is to reserve it for simple either/or decisions - nested ternaries are especially hard to read.

In real-world development it comes up constantly for simple branching, such as assigning a value to a variable or choosing between two messages.

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

๐Ÿงช This site can't compile or run Swift 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)