2.3. Tuples

A Tuple is a collection of different elements of different data types stored together in the same place. It may sound like an array, but it is not exactly an array. The differences are:

  • An array contains values of the same data type. However, a tuple can hold values of different data types together.

  • You can add and remove elements from an array. However, you cannot add or remove elements once you create a tuple. You can change the elements, but you cannot change the types of the elements.

Creating a new tuple:

We can create a tuple by putting the elements into parenthesis, like:

// Simple tuple
var myTuple = ("Mark", 20)
// We can also define the names of the elements
var yourTuple = (name:"Julie", age:23)

//print tuples
print("myTuple: \(myTuple), yourTuple: \(yourTuple)")

It prints:

myTuple: ("Mark", 20), yourTuple: (name: "Julie", age: 23)

Accessing elements in a tuple:

You can access the elements in a tuple using their positions (similar to an array) or using their names. For example,

// accessing tuple elements
print("yourTuple's elements:\n first element = \(yourTuple.0),\n second element = \(yourTuple.age)")

It outputs:

Here we can see that yourTuple.0 is the first element of the tuple, which is the same as yourTuple.name; and yourTuple.age is the second element of the tuple.

Changing values:

You can change the values of the elements of a Tuple, like:

It prints:

Please note: you can modify the values of an element; however, you cannot change the data type.

Try writing: yourTuple.age="thirty four" 😉

Last updated

Was this helpful?