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
.
</>
Copy
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.
</>
Copy
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.
</>
Copy
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.
</>
Copy
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
Conclusion
In this Swift Tutorial, we learned to initialize, access, and modify Swift Tuples with examples.