Swift Tuples

Tuples are similar to collection datatypes like array and dictionaries. Tuples can contain values of any data type. Then, the difference between collection and tuple is, we can not add or delete an element from a tuple.

Do you wanna know the syntax and how it should be declared. Generally, Tuples are defined as a comma separated values, within a pair of parentheses.
let nameAndAge = (“Tom Tom “, 41)  
The (“Tom Tom”,41) tuple groups together a String and an Int to give the name and age of a person.
It can be described as “a tuple of type (String, Int)”.
You can create tuples from any permutation of data types, and they can contain many different data types as you like. There’s nothing stopping you from having a tuple of type (Int, Int, Int), or (String, Bool), or indeed any other permutation you require.

When to Use a Tuple:

Tuples are particularly useful as the return value of a function. A function that tries to retrieve a web page might return the (Int, String) tuple type to describe the success or failure of the page retrieval. By returning a tuple with two distinct values, each of a different type, the function provides more useful information about its outcome than if it could only return a single value of a single type.

Decomposing and accessing values from a Tuple:

We can decompose a tuple’s contents into separate constants or variables, later we then access it as usual:
let  (name,age) = nameAndAge  // to know more about let , please visit variables in swift3
println(“Age is \(age)”)
// prints “Age is 41”
println(“Name is \(name)”)
// prints “Name is Tom Tom”
Access the individual element values in a tuple using index numbers starting at zero:
println(“Name  is \(nameAndAge .0)”)
// prints “Name is Tom Tom”
println(“Age is \(nameAndAge .1)”)
// prints “Age is 41”

Alternatively, We can name the individual elements in a tuple when the tuple is defined like below,

let nameAndAge = (name : “Tom Tom”,age:41)
If we name the elements in a tuple, we can use the element names to access the values of those elements,
println(“Name is \(nameAndAge.name)”)
// prints “Name is Tom Tom”
println(“Age is \(nameAndAge.age)”)
// prints “Age is 41”

Note: If we need only some of the tuple’s values, then we can ignore parts of the tuple with an underscore (_) when we decompose the tuple:
let (name, _) = nameAndAge



Leave a Reply

Your email address will not be published. Required fields are marked *