Swift Programming Tutorial: How to Make a Function Return Multiple Values
Tip: Use Tuples
This article is part of my Swift Programming Tutorial series. I highly recommend understanding the concept of both functions and tuples before proceeding.
In Swift, returning multiple values from a function is as easy as making a custom gift box where you wrap everything up in a nice little tuple! Tuples let you pack multiple values of different types into a single, cohesive package, which you can then pass around as one unified entity. Let’s dive into an example to make it fun and memorable.
The Basics: Return Multiple Values with a Tuple
Imagine we’re working with a function that calculates both the area and perimeter of a rectangle. Instead of creating two separate functions, let’s make one function that returns both values at once. Here’s how that would look:
func calculateRectangleProperties(width: Double, height: Double) -> (area: Double, perimeter: Double) {
let area = width * height
let perimeter = 2 * (width + height)
return (area, perimeter)
}
What’s happening here?
- The return type of
calculateRectangleProperties
is a tuple(area: Double, perimeter: Double)
. This means the function will…