DEV Community

Cover image for Tuples in Swift
Lori "Lei" Boyd
Lori "Lei" Boyd

Posted on

3 1

Tuples in Swift

I recently started to dive into the world of IOS development. As I was taking a tour on the documentation website, I came across a data type I've never heard before. "What's a tuple???", I asked myself.

Alt Text

For context, I was reading a section on functions to get familiar with the syntax. The following code is a function that calculates the minimum, maximum, and sum of a given array of integers.

func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
    var min = scores[0]
    var max = scores[0]
    var sum = 0

    for score in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        sum += score
    }

    return (min, max, sum)
}
let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
print(statistics.min, "the minimun")
// Prints "3 the minimum"
print(statistics.sum, "the sum")
// Prints "120 the sum"
print(statistics.1, "the max")
// Prints "100 the max"

A Tuple is defined by Swift's documentation as a comma-separated list of types, enclosed in parentheses and is commonly used to return multiple values. The above code uses dot notation to call the variables placed in the tuple and can be called by name or index. To me, this resembles a mashup of a Javascript Object and an array.

You can also name the elements inside of a tuple like so: var aTuple = (age: 24, name: "Lei") and reference them with aTuple.age which will return 24.

Alt Text

A tuple can contain zero or more types. Andyy Hope states an interesting fact on tuples over on his blog that void is just a typealias for an empty tuple.

As I'm journeying through the language of Swift, I'm sure I'll many more gems that make Swift uniquely great.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →