Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Decompose Tuples in Swift
Written by Team Kodeco

In Swift, you can decompose a tuple into separate variables or constants. This allows you to easily access the individual elements of the tuple without having to access them by their index.

Here’s an example of how to decompose a tuple:

let tuple = (1, "apple")
let (number, fruit) = tuple
print(number)  // 1
print(fruit)  // "apple

You can also decompose a tuple in a single line:

let (number, fruit) = (1, "apple")

You can also ignore certain elements of the tuple by using the _ character:

let (_, fruit) = (1, "apple")
print(fruit)  // "apple

You can also use tuple decomposition in control flow statements:

let tuple = (1, "apple")
if case (_, "apple") = tuple {
  print("This tuple contains an apple.")
}
© 2024 Kodeco Inc.