17. Tuples in Swift

Tuple is quite simple and very powerful feature of Swift programming language. Tuple is a special type of array where you can contain different type of data in one place. The item stored in tuple can be Integers with Strings or Float with Double or all in one tuple.

Tuple initialization and access

Declaration and initialization of tuple is as follow.

let myTuple = (3.141, "Pie Value",  350)

Now your tuple is ready. You can access tuple values in sequence, same like array sequence starts from 0.

var value1 = myTuple.0
var value2 = myTuple.1
var value3 = myTuple.2

It is also possible to assign name to each value.

let myTuple = (pie: 3.141, message: "Pie Value", area: 350)

Later, these names can be used as reference to access relevant values


Alternatively, all of the values can be accessed and assigned to variables or constants.

let(doubleValue, stringValue, intValue) = myTuple

println("Tuple Double Value \(doubleValue) ")
println("Tuple String Value \(stringValue) ")
println("Tuple Integer Value \(intValue) ")

The same technique can be used to extract selected values. You can replace the variable with ‘_ ‘ underscore character

let(doubleValue, _ , intValue) = myTuple

println("Tuple Double Value \(doubleValue) ")
println("Tuple Integer Value \(intValue) ")


Tuple and function return type

Can you return more than one values from function, the answer is yes with help of tuple. You can declare the tuple as return type of the function.

Declare a function which returns a tuple (String and Integer)

func myTupleFunction() -> (String , Int)

Initialize two variables and assign some values to it and return these values in form of tuple.

func myTupleFunction() -> (String , Int){
    var name = "Khan"
    var age = 20
    return (name , age)

Catch tuple in a variable or constant and access tuple’s values with index.

let result = myTupleFunction()
println("My name is \(result.0) and my age is \(result.1)")



Download file from GitHub