Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Optional Ternary Operator in Swift
Written by Team Kodeco

The Optional Ternary Operator, also known as the ternary conditional operator, is a shorthand way of handling optionals in Swift. It allows you to concisely check if an optional has a value, and perform different actions based on whether it does or not.

Here’s an example of how to use the Optional Ternary Operator:

let optionalInt: Int? = 5
let result = optionalInt != nil ? optionalInt! : 0
print(result) // Output: 5

In this example, the Optional Ternary Operator checks if the optional optionalInt has a value. If it does, it unwraps the optional and assigns the value to the constant result. If the optional is nil, it assigns the value of 0 to the constant result.

Note that although this works, your code is usually more readable if you use optional binding or the nil-coalescing operator instead.

© 2024 Kodeco Inc.