Swift Introduction | Structures, Enumerations, and Tuples | Tuples

Tuples have already appeared several times. A tuple groups multiple values, including values of different types, in one place. Write a tuple as follows.

(value1, value2, ...)

Create a tuple by writing comma-separated values inside parentheses. Retrieve its values by adding a dot and an index to the variable that stores the tuple, such as tuple.1.

Using indexes can cause mistakes if you do not clearly understand the order of the values. Like a dictionary, a tuple can also assign names to its values.

(key1 : value1, key2 : value2, ...)

For a tuple written in this form, retrieve a value with a key instead of a number, such as tuple.key. You can think of it as similar to the difference between an array and a dictionary.

The following example uses tuples.

func MakeTuple(name:String, age:Int)->(name:String, age:Int) {
    return (name:name, age:age)
}

var me = MakeTuple("Yamada", age: 99)
var you = MakeTuple("Hanako", age: 36)

print(me.name)
print(you.age)

This example provides a function that creates tuples in a fixed format, then creates tuples and displays their values.

Tuples let you freely choose their value structure. That freedom can make their contents inconsistent, but a function such as this one lets you create tuples with the same format.