Swift Tuples

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

Following is a simple example of Swift Tuple.

var player1 = (45, "Rohit")

The tuple player1 has two values. The first is integer and the second is string: different datatypes.

You can have a mix of any datatypes in a single tuple.

Accessing a Tuple

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

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

Named Tuple

You can also have names for the values inside tuple. And access those values using names.

var player2 = (jersyNumber: 15, name: "Kohli")
 var jersyNumber = player2.jersyNumber
 var name = player2.name

Edit Tuple

You can edit values at value level inside a tuple.

var player1 = (1, "Rohit")
player1.0 = 2

Example 1 – Swift Tuple Initialization & Access Values

This example demonstrates how to initialize and access values of a Tuple in Swift.

main.swift

//tuple initialization
var player1 = (45, "Rohit")
//access values of tuple
print( player1 )
print( player1.0 )
print( player1.1 )

/* named values in tuple */
//tuple initialization
var player2 = (jersyNumber: 15, name: "Kohli")
//access values inside tuple using names
print( player2 )
print( player2.jersyNumber )
print( player2.name )

Output

(45, "Rohit")
45
Rohit
(jersyNumber: 15, name: "Kohli")
15
Kohli

Example 2 – Modify Values inside Tuple

In this example, we will modify the values inside tuple. We will edit the first value or jersyNumber for the player tuples.

main.swift

//tuple initialization
var player1 = (1, "Rohit")
player1.0 = 2
print( player1 )

/* named values in tuple */
var player2 = (jersyNumber: 15, name: "Kohli")
player2.jersyNumber = 27
print( player2 )

Output

(2, "Rohit")
(jersyNumber: 27, name: "Kohli")

Conclusion

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