DEV Community

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

Posted on

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.

Top comments (0)