Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Tuples in Switch Statements in Swift
Written by Team Kodeco

In Swift, you can use tuples in switch statements to match multiple values at once. This allows you to write more concise and expressive code.

Here’s an example of how to use a tuple in a switch statement:

let tuple = (1, "apple")

switch tuple {
case (0, "apple"):
    print("This is an apple with a value of 0.")
case (1, "apple"):
    print("This is an apple with a value of 1.")
default:
    print("This is not an apple or the value is not 0 or 1.")
}
// Output: "This is an apple with a value of 1.

You can also use the where keyword to match specific conditions:

let tuple = (1, "apple")

switch tuple {
case (let value, "apple"):
    print("This is an apple with a value of \(value).")
case (_, "banana"):
    print("This is a banana.")
default:
    print("This is neither an apple nor a banana.")
}
// Output: "This is an apple with a value of 1.
© 2024 Kodeco Inc.