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
var player = (45, "Rohit")
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
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
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
- Swift – Initialize a Tuple
- Swift – Get Element of a Tuple at Specific Index
- Swift – Update Element of a Tuple at Specific Index
- Swift – Initialize a Tuple with Labels for Values in it
- Swift – Access Values of a Tuple using Labels
In this Swift Tutorial, we learned to initialize, access, and modify Swift Tuples with examples.