0
0
Swiftprogramming~5 mins

Functions returning tuples in Swift

Choose your learning style9 modes available
Introduction

Functions can send back more than one value at a time using tuples. This helps keep related values together in a simple package.

When you want to return multiple pieces of information from a function, like a name and age.
When you want to return different types of values together, such as a number and a string.
When you want to return a status and a result from a process.
When you want to group small related data without creating a new type or class.
Syntax
Swift
func functionName() -> (Type1, Type2, ...) {
    // code
    return (value1, value2, ...)
}

The tuple types are listed inside parentheses after the arrow ->.

You return the values as a tuple using parentheses with commas.

Examples
This function returns two integers as a tuple representing coordinates.
Swift
func getCoordinates() -> (Int, Int) {
    return (10, 20)
}
This function returns a tuple with named elements for clarity.
Swift
func getUserInfo() -> (name: String, age: Int) {
    return ("Alice", 30)
}
This function returns the quotient and remainder of a division as a tuple with names.
Swift
func divide(_ a: Int, _ b: Int) -> (quotient: Int, remainder: Int) {
    return (a / b, a % b)
}
Sample Program

This program defines a function that returns a tuple with a name and age. It then calls the function and prints the values using the tuple's named elements.

Swift
func getPerson() -> (name: String, age: Int) {
    return ("Bob", 25)
}

let person = getPerson()
print("Name: \(person.name), Age: \(person.age)")
OutputSuccess
Important Notes

You can access tuple elements by position (like tuple.0) or by name if you provide names.

Tuples are great for small groups of values but for bigger data, consider using structs.

Summary

Functions can return multiple values grouped as tuples.

Tuples can have named or unnamed elements.

Use tuples to keep related values together simply and clearly.