Swift – Initialize a Tuple with Labels for Values

To initialize a Tuple with labels for values in Swift, provide the labels before these values followed by a colon.

The syntax to specify labels for values of a tuple is

</>
Copy
(label1: value1, label2: value2)

Examples

In the following program, we initialize a Tuple x with values, where each value is given a label.

main.swift

</>
Copy
var x = (a: "Hello", b: 35, c:true)
print(x)

Output

Swift - Initialize a Tuple with Labels for Values

Labelling a value in Tuple is optional. So, we may label only some of the values in the Tuple.

main.swift

</>
Copy
var x = (a: "Hello", 35, true)
print(x)

Here, we have labelled only one value of the Tuple x.

Output

Swift - Initialize a Tuple with Labels for only some Values

We can access the labelled values using the labels with the help of dot operator.

main.swift

</>
Copy
var x = (a: "Hello", b: 35, c:true)
print(x.a)
print(x.b)
print(x.c)

Output

Conclusion

In this Swift Tutorial, we have learned how to access values of a Tuple using labels, in Swift programming.