Swift Tuple With Examples

Swift tuple is a container to hold multiple values. Swift Arrays are largely homogeneous data types. Same isn’t the case with tuples. Let’s get started by launching the Swift Playground in XCode.

Swift Tuple

Tuples can hold zero or more values. The values need not be of the same type. Tuples in Swift are like mini structs and should be used for storing temporary values only.
Tuples are handy when we have to return multiple values from a function.

Creating a Tuple

Values in a tuple are comma separated as shown below.

Swift-Tuple-Example

  • Creating a tuple is similar to defining variables. All we need to do is set the values separated by commas in parentheses.
  • Type of the tuple is inferred from the definition itself.
  • The type of a Swift Tuple is the type of all of its values.
  • To access the values from the tuple we need to use the dot syntax followed by the index of the value.
  • Instead of using indexes to access the elements, we can set names to the tuple elements.

In order to define an empty tuple you just need to do : var voidTuple = (). It has the type (Void)

We can create tuples by defining the types as shown below:

Swift Tuple Element Names

We can name each element of the tuple similar to how parameters are named in Swift Functions

The type of the above tuple is (String, String, Int).

Decomposing Swift Tuple

We can retrieve and set values from a tuple to variables and constants. This is known as decomposing tuples.

  • Setting an underscore means you’re ignoring that value from the tuple.
  • This is a good way to define multiple variables and constants from tuples.
  • The constants defined in the let statement can’t be modified.

Using the above method we can also assign multiple values at the same time.

Swapping two elements using Swift Tuples

Provided they are of the same type, we can swap the values in two variables using a tuple

Swift Tuples are Value Types

Tuples in Swift are value types and not reference types.

As it is evident from the above example, values changed in the new tuple have no impact over the earlier one from which they were copied.

Note: Values present in a let tuple cannot be modified.

Swift Tuple inside another tuple

Tuples are compound types. One Tuple can be nested inside another.

Returning Multiple Values From a Function

Using Swift tuple we can return multiple values from a function as shown below.

To set the element names in the returned tuple, we need to explicitly set them in the tuple type definition itself.

That’s all for a quick roundup on the swift tuple.

By admin

Leave a Reply

%d bloggers like this: