Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Ternary Operator to Conditionally Assign Values
Written by Team Kodeco

In Swift, you can use the ternary operator to conditionally assign values to variables or constants based on a certain condition. The ternary operator is a shorthand way to write a basic if-else statement and takes the following form:

condition ? valueIfTrue : valueIfFalse

For example, to assign a value of “Even” to a variable if a given number is even and “Odd” if it is odd, you can use the following syntax:

let number = 5
let evenOrOdd = number % 2 == 0 ? "Even" : "Odd"

In this example, evenOrOdd is a variable that has been assigned the value “Odd” because the number 5 is odd.

The ternary operator can make your code more concise and readable, as it allows you to write a simple if-else statement in a single line.

© 2024 Kodeco Inc.