Menu
Coddy logo textTech

Ternary Operator

Part of the Fundamentals section of Coddy's Swift journey — lesson 25 of 86.

The ternary operator provides a shorthand way to choose between two values based on a condition. It's called "ternary" because it takes three parts: a condition, a value if true, and a value if false.

The syntax follows this pattern: condition ? valueIfTrue : valueIfFalse

let age = 20
let status = age >= 18 ? "Adult" : "Minor"
print(status)  // Adult

In this example, Swift checks if age >= 18. Since it's true, status gets assigned "Adult". If the condition were false, it would receive "Minor" instead.

The ternary operator is particularly useful when you need to assign one of two values based on a simple condition:

let score = 75
let result = score >= 60 ? "Pass" : "Fail"
print(result)  // Pass
let temperature = 15
let weather = temperature > 25 ? "Hot" : "Cool"
print(weather)  // Cool

You can use any condition that evaluates to a Boolean, including the logical operators you've learned. Keep the ternary operator for simple, clear choices — for more complex logic, other approaches work better.

challenge icon

Challenge

Easy

You are provided with the following variables:

let balance = 150
let withdrawAmount = 200

Use the ternary operator to determine the transaction status and print the result.

If balance is greater than or equal to withdrawAmount, the status should be "Approved". Otherwise, the status should be "Insufficient funds".

Print the status on a single line.

Cheat sheet

The ternary operator provides a shorthand way to choose between two values based on a condition. It takes three parts: a condition, a value if true, and a value if false.

Syntax: condition ? valueIfTrue : valueIfFalse

let age = 20
let status = age >= 18 ? "Adult" : "Minor"
print(status)  // Adult

More examples:

let score = 75
let result = score >= 60 ? "Pass" : "Fail"
print(result)  // Pass

let temperature = 15
let weather = temperature > 25 ? "Hot" : "Cool"
print(weather)  // Cool

Try it yourself

let balance = 150
let withdrawAmount = 200

// TODO: Write your code below
// Use the ternary operator to determine the status based on balance and withdrawAmount
// If balance >= withdrawAmount, status should be "Approved"
// Otherwise, status should be "Insufficient funds"

// Print the status
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals