Swift Tuples
By Flavio Copes
Learn how to use tuples in Swift to group several values together, name and decompose their elements, return multiple values, and even swap variables.
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 Related posts about swift: