Skip to content

Swift Tuples

New Course Coming Soon:

Get Really Good at Git

This tutorial belongs to the Swift series

Tuples are used to group multiple values into a single collection. For example we can declare a variable dog containing a String and an Int value:

let dog : (String, Int)

And we can initialize them with a name and an age

let dog : (String, Int) = ("Roger", 8)

But as with any other variable, the type can be inferred during initialization:

let dog = ("Roger", 8)

You can use named elements:

let dog = (name: "Roger", age: 8)

dog.name //"Roger"
dog.age //8

Once a tuple is defined, you can decompose it to individual variables in this way:

let dog = ("Roger", 8)
let (name, age) = dog

and if you need to just get one of the values, you can use the special underscore keyword to ignore the other ones:

let dog = ("Roger", 8)
let (name, _) = dog

Tuples are an awesome tool for various needs.

The most obvious one is a short way to group similar data.

Another one if those needs is returning multiple items from a function. A function can only return a single item, so a tuple is a convenient structure for that.

Another handy functionality allowed by tuples is swapping elements:

var a = 1
var b = 2

(a, b) = (b, a)

//a == 2
//b == 1
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my Swift Handbook

Here is how can I help you: