Swift Tuples

In this tutorial you will learn about the Swift Tuples and its application with practical example.

Swift Tuples

Tuple is an ordered list of zero or more comma-separated values (items or elements), where elements can be of different types. Tuple allows you to represent a collection of values that are closely linked to each other.

Example:-

Creating a Tuple

In Swift, a tuple is defined within a pair of parentheses () where items are separated by commas. Tuple declaration is same as an array literal, except the parenthesis (instead of square brackets), and it can take values of any type.

Example:-

Named Tuple Elements

In Swift, there is another way to define a tuple where you can use named key for tuple elements.

Example:-

Tuple Types

The type of any tuple can be determined by it element’s value. So (“W3Adda”, 1) will be of type (String, Int). If the tuple has only one element then the type of that tuple is the type of the element.

Example 1:-

Here, we have declared a tuple with type (String, Int)

Example 2:-

Here, we have declared a named tuple with type (String, Int)

Empty Tuple

Tuple with no element is termed as empty tuple, it can be represented using pair of parentheses () with no elements.

Reading Tuple

In Swift, Commonly there are two ways we can accessing the data in a tuple by index or by name.

Recommended:-  Swift Dictionaries

by index:-

We can access the tuple element’s values using the dot(.) notation followed by the index of the value. Tuple index value starts from zero(0).

Example:-

Output:-

by name:-

In Swift, you can assign name to the tuple elements and then can use those names to access them as following –

Example:-

Output:-

Multiple assignment

A tuple can be used to initialize more than one variable in once as following –

Example:-

here, tuple values being assigned to variables a, b and c correspondingly.

Returning multiple values

In Swift, tuple can be used to return multiple values from a swift function as following –

Example:-

Decomposing Tuples

In Swift, a tuple elements can be decomposed into separate constants or variables and can be used further as normal constant or variables.

Example:-

here, we have created a tuple named siteInfo with two elements , later in next line we have assigned its elements to separate variables named siteName and siteRank correspondingly. If you only want to extract some of the tuple values then you can use an underscore (_) in place of the element you want to ignore when you decompose the tuple.

Recommended:-  Swift For in Loop

Example 1:-

Example 2:-

Nested Tuple(Tuple inside another tuple)

In Swift, a tuple can contain another tuple as following –

Example:-

Output:-

In this tutorial we have learn about the Swift Tuples and its application with practical example. I hope you will like this tutorial.