Tuple
A tuple can combine multiple (and possibly different) types to form a new composite type. The tuple type is represented as (T1, T2, ..., TN), where T1, T2, ..., TN can be any type. The types within the tuple type are separated by commas (,) and must contain at least two elements. For example, (Int64, Float64) represents a tuple type with two elements (a pair), while (Int64, Float64, String) represents a tuple with three elements (a triplet).
The length of a tuple is fixed, meaning that once a tuple instance is defined, its length cannot be changed.
The tuple is an immutable type, meaning that once a tuple instance is defined, its content cannot be changed. The following example results in a compilation error:
var tuple = (true, false)
tuple[0] = false // Error, 'tuple element' cannot be assigned
Literals of the Tuple Type
A literal of the tuple type is represented as (e1, e2, ..., eN), where e1, ..., eN are expressions. The expressions within the tuple are separated by comma (,). In the following example, two variables are declared and initialized with tuple literals: variable x is a tuple of type (Int64, Float64) and variable y is a tuple of type (Int64, Float64, String).
let x: (Int64, Float64) = (3, 3.141592)
let y: (Int64, Float64, String) = (3, 3.141592, "PI")
The elements of a tuple can be accessed using their indices with the notation t[index], where t is a tuple, and index is a non-negative integer that is smaller than the length of the tuple.
If the index does not satisfy these conditions, a compilation error will be reported. In the following example, the first and second elements of the tuple pi are accessed using pi[0] and pi[1] respectively.
main() {
var pi = (3.14, "PI")
println(pi[0])
println(pi[1])
}
Compiling and executing the code above produces the following output:
3.140000
PI
In an assignment expression, tuples can be used for multiple assignment. For details, see Assignment Operators.
Type Parameters of a Tuple
The fields of a tuple can be named as shown in the following example. Function getFruitPrice returns a tuple in which the first element is named name and the second element is named price.
func getFruitPrice (): (name: String, price: Int64) {
return ("banana", 10)
}
For a tuple type, you can write only type parameter names or omit them entirely. The type parameter names cannot be used as variables or used to access elements in the tuple.
let a: (name: String, Int64) = ("banana", 5) // Error
let b: (name: String, price: Int64) = ("banana", 5) // OK
b.name // Error