0
0
Swiftprogramming~5 mins

Tuples for grouped values in Swift

Choose your learning style9 modes available
Introduction

Tuples let you keep several values together in one simple package. This helps when you want to return or pass multiple related values at once.

When you want to return multiple values from a function without making a new type.
When you need to group a few related values temporarily.
When you want to quickly label a small set of values for clarity.
When you want to pass multiple values as one unit to another part of your code.
Syntax
Swift
let tupleName = (value1, value2, value3)

// Or with labels:
let tupleName = (label1: value1, label2: value2, label3: value3)

You can access tuple values by position (e.g., tupleName.0) or by label (e.g., tupleName.label1) if labels are used.

Tuples are fixed in size and type once created.

Examples
A tuple with three values accessed by position.
Swift
let person = ("Alice", 30, true)
print(person.0)  // Prints "Alice"
print(person.1)  // Prints 30
A tuple with labels for clearer access.
Swift
let person = (name: "Bob", age: 25, isStudent: false)
print(person.name)  // Prints "Bob"
print(person.age)   // Prints 25
Using a tuple to return multiple values from a function.
Swift
func getCoordinates() -> (x: Int, y: Int) {
    return (x: 10, y: 20)
}

let point = getCoordinates()
print(point.x)  // Prints 10
print(point.y)  // Prints 20
Sample Program

This program defines a function that returns a tuple with user info. Then it prints each value using the tuple labels.

Swift
func getUserInfo() -> (name: String, age: Int, isMember: Bool) {
    return (name: "Emma", age: 28, isMember: true)
}

let user = getUserInfo()
print("Name: \(user.name)")
print("Age: \(user.age)")
print("Member: \(user.isMember)")
OutputSuccess
Important Notes

Tuples are great for small groups of values but not for complex data. For bigger data, use structs or classes.

Tuple labels improve code readability and help avoid mistakes.

Summary

Tuples group multiple values into one simple package.

You can access tuple values by position or by label.

They are useful for returning multiple values from functions quickly.