Swift: Ternary Conditional Operator

Ternary Conditional Operator in Swift:

A typical if/else statement can be quite long, with at least 5 lines of code. Many programmers prefer to use a shorter syntax and keep their code as short as possible. We can use Swift’s ternary conditional operator to reduce the number of if/else statements.

The ternary conditional operator, denoted by a ?, is a more compact version of the standard if/else statement. Depending on the boolean result of the condition, it executes one of two expressions.

A ternary conditional is made up of three parts, as shown below:

X ? Y :Z
  • X is the condition to check for
  • Y is the statement to use if the condition is true
  • Z is the statement to use if the condition is false

Let’s say we want to see if a customer’s order was delivered and then send them a message. The following is an example of an if/else statement:

var OrderDelivered = true; 
if OrderDelivered {
  print("Order was Delivered.");
} else {
  print("There was an issue.");

The first code block executes because the value of our condition is true, and Order was Delivered. will be printed.

With a little ternary magic, we can reduce our code to a single line, a one liner, and get the same result:

OrderDelivered ? print("Order was Delivered.") : print("There was an issue.");

Although the ternary conditional operator allows us to write shorter code, excessive use of this syntax can make your code difficult to read. As a result, use it sparingly!

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: