0
0
Swiftprogramming~5 mins

Ternary conditional operator in Swift

Choose your learning style9 modes available
Introduction

The ternary conditional operator helps you choose between two values quickly based on a condition. It makes your code shorter and easier to read.

When you want to assign a value based on a simple yes/no question.
When you want to print one message if something is true, and another if it is false.
When you want to set a color or style depending on a condition.
When you want to return one of two values from a function quickly.
When you want to simplify an if-else statement that only picks between two options.
Syntax
Swift
condition ? valueIfTrue : valueIfFalse

The condition is a question that results in true or false.

If the condition is true, the operator returns valueIfTrue, otherwise it returns valueIfFalse.

Examples
This checks if age is 18 or more. If yes, canVote is "Yes", otherwise "No".
Swift
let age = 18
let canVote = age >= 18 ? "Yes" : "No"
Here, if score is 60 or more, grade is "Pass", else "Fail".
Swift
let score = 75
let grade = score >= 60 ? "Pass" : "Fail"
Depending on isSunny, it suggests what to take.
Swift
let isSunny = false
let weather = isSunny ? "Take sunglasses" : "Take umbrella"
Sample Program

This program checks if the temperature is above 25 degrees. If yes, it suggests wearing shorts; otherwise, pants.

Swift
import Foundation

let temperature = 30
let advice = temperature > 25 ? "Wear shorts" : "Wear pants"
print("Temperature: \(temperature)°C")
print("Advice: \(advice)")
OutputSuccess
Important Notes

Use the ternary operator only for simple conditions to keep code clear.

For complex decisions, prefer if-else statements for better readability.

Summary

The ternary operator chooses between two values based on a condition.

It is a shortcut for simple if-else assignments.

Use it to make your code shorter and easier to read when the choice is simple.