Swift Tuples

Tuples are used to group values of different datatypes under a single variable name.

The following is an example of Swift Tuple stored in a variable named player.

var player = (45, "Rohit")

The Tuple player has two values. The first is an Int and the second is a String. We can have a mix of any datatypes in a single Tuple.

Accessing a Tuple

We can access a tuple using the dot operator and index.

var player = (45, "Rohit")
var jersyNumber = player.0
var name = player.1

Named Tuple

We can also have names for the values inside tuple, and access those values using names.

var player = (jersyNumber: 18, name: "Kohli")
var jersyNumber = player.jersyNumber
var name = player.name

Edit Tuple

We can assign new values to the elements in a Tuple by accessing them using dot operator and assigning a new value.

var player = (1, "Rohit")
player.0 = 45

More Swift Tuple Tutorials


In this Swift Tutorial, we learned to initialize, access, and modify Swift Tuples with examples.