What are Tuples

suggest change

Tuples group multiple values into a single compound value. The values within a tuple can be of any type and do not have to be of the same type as each other.

Tuples are created by grouping any number of values:

let tuple = ("one", 2, "three")

// Values are read using index numbers starting at zero
print(tuple.0) // one
print(tuple.1) // 2
print(tuple.2) // three

Individual values can also be named when the tuple is defined:

let namedTuple = (first: 1, middle: "dos", last: 3)

// Values can be read with the named property
print(namedTuple.first)  // 1
print(namedTuple.middle) // dos

// And still with the index number
print(namedTuple.2)      // 3

Element names can also be written in the type. An element can be optional, and the tuple value itself can be optional. Because numbers is optional, read its elements with ?:

var numbers: (optionalFirst: Int?, middle: String, last: Int)?

//Later On
numbers = (nil, "dos", 3)

print(numbers?.optionalFirst) // nil
print(numbers?.middle) // Optional("dos")
print(numbers?.last) // Optional(3)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents