Learning w/ Swift

What are tuples in Swift and when are they useful?

Swift has many different data structures that allow you to group multiple values into a single compound value. Between arrays, sets, dictionaries and tuples, swift gives us a lot of options with their own benefits and drawbacks.

In this post I’ll be talking about tuples, which unlike arrays or dictionarys, can contain a mix of different data types.

Tuples are particularly useful when you need to bundle related data together temporarily, and their elements can be of different types. For example:

  • Returning multple values from a function
func getUserInfo() -> (String, Int) {
    return ("John Doe", 30)
}

let (name, age) = getUserInfo()
print("Name: \(name), Age: \(age)")
  • Grouping data that doesn’t warrent creating a custom struct
let coordinates = (x: 10, y: 20)
print("X: \(coordinates.x), Y: \(coordinates.y)")
  • Assigning multiple values at once
let (a, b, c) = (1, 2, 3)
  • Function parameters
func displayCoordinates(coordinates: (x: Int, y: Int)) {
    print("X: \(coordinates.x), Y: \(coordinates.y)")
}

displayCoordinates(coordinates: (x: 15, y: 25))
  • Pattern matching
let point = (x: 5, y: 10)
switch point {
case (0, 0):
    print("At the origin")
case (_, 0):
    print("On the x-axis")
case (0, _):
    print("On the y-axis")
default:
    print("Somewhere else")
}

Tuples are extremely flexible, but are best used as small, temporary groupings of values.