Wednesday, July 2, 2014

Tuples in Swift Language

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. In this example, (12, "student Name") is a tuple that describes an student data.

let studentdata = (12, "John")

The (12, "John") tuple groups together an Int and a String to give the student data two separate values: a number and a name of student. It can be described as “a tuple of type (Int, String)”.

You can create tuples from any permutation of types, and they can contain as many different 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. You can decompose a tuple’s contents into separate constants or variables, which you then access as usual:

let (rollnumber, studentname) = studentdata
println("The roll number is \(rollnumber)")
// prints "The roll number is 12"

println("The student name is \(studentname)")
// prints "The student name is John"

Alternatively, access the individual element values in a tuple using index numbers starting at zero:
println("The roll number is \(studentdata.0)")
// prints "The roll number is 12"
println("The student name is \(studentdata.1)")
// prints "The student name is John"

You can name the individual elements in a tuple when the tuple is defined:
let studentinfo = (rollNo: 20, Name: "Howdy")
If you name the elements in a tuple, you can use the element names to access the values of those elements:

println("The rollNo is \(studentinfo.rollNo)")
// prints "The rollNo  is 20"

println("The Name is \(studentinfo.Name)")
// prints "The Name is Howdy"

Tuples are particularly useful as the return values of functions. 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.

No comments:

Post a Comment