Swift Tuple

Stefano Frosoni
If let swift = Programming!
3 min readNov 12, 2018

--

Tuples provide a way to group multiple values together representing them as single compound value. The values in a tuple can be of any type and the same tuple can contain different types of items. Tuples occupy the space between Structs and Dictionaries. Tuple are value types as Structs but they can be created on the fly as Dictionaries (but differently from dictionaries they cannot be used as Dictionary keys). There’s no comparable construct in Objective-C.

Create a tuple:

Tuples are defined using “( )”. Below you can see a simple tuple declaration:

Above we have a tuple consisting of an Int and a String. You can access elements of a tuple by position using the index numbers that start from 0.

You can decompose a tuple into its parts using the assignment operator. You can use “ _ ” to indicate fields that you don’t care about; in the example above we have extracted only the value of the second element into a constant “message”.

You can also name the variables of a tuple while declaring , and use those names to refer to them. An element name is an identifier followed by a colon “:”.

Tuples in Swift are typed; in the example above Swift inferred its type as (Int, String) and that means that whenever you try to update the tuple, your assignment must match the type signature.

Tuple are value types

As we said before Tuple are value types not reference types. So when you initialise a variable tuple with another one it will create a copy. Let’s see an example:

Tuple inside tuple

We can create Tuples that contains other tuple as this below:

Where to use tuples

The most common use-case for tuples is to return multiple values from a function. Below an exaple:

Sources: Swift.Org

Thanks for your time and I hope you find this article useful.

--

--