Chapter 12 : Tuples

Topics Covered :

1. What are Tuples
2. Examples

# Tuples

Tuples are a group of multiple values into a single compounded value.

What is a Tuples

Tuples can contain values of any data type. It is not necessary that the values contained in Tuples are of same type.

Syntax : var/let tupleName = (element1,element2, ... , elementN)

Type Aliases can be used when you refer to existing datatypes that you want to rename to more appropriate one,

Example : var value = (100000, "100,0000","One hundred thousand")

In the above example we have a variable assigned a tuple with types (Int, String, String)

``````
//
//  main.swift
//  Swift Tutorials 2014-15
//  Tuples in Swift example
//
//  Created by Code2care on 15/09/14.
//

var value = (100000, "100,0000","One hundred thousand")

println("\(value)")
println("\(value.0)")
println("\(value.1)")
println("\(value.2)")

```
```
Output :

(100000, 100,0000, One hundred thousand)
100000
100,0000
One hundred thousand
Program ended with exit code: 0

You can even assign a tuple to another variable, you can access a tuple var individual elements by using . (dot) followed by the index of the elements.

``````
//
//  main.swift
//  Swift Tutorials 2014-15
//  Tuples in Swift example
//
//  Created by Code2care on 15/09/14.
//

var value = ("Name", "Steve Jobs")

var valueDuplicate = value

println("\(valueDuplicate)")
println("\(valueDuplicate.0)")
println("\(valueDuplicate.1)")

```
```
Output :

(Name, Steve Jobs)
Name
Steve Jobs
Program ended with exit code: 0

#### Assigning Names to individual elements for tuples :

Syntax : let/var tupleName = (element1Name:value , element2Name:value .... elementNName:value)

You can access individual elements using tupleName (dot) elementName

Example : tupleName.element1Name

``````
//
//  main.swift
//  Swift Tutorials 2014-15
//  Tuples in Swift example
//
//  Created by Code2care on 15/09/14.
//

var tulipExample = (digit:101, inWords:"One Hundred and One")

println("\(tulipExample)")

//Accessing elements using Element Name
println("\(tulipExample.digit)")
println("\(tulipExample.inWords)")

```
```
Output :

(101, One Hundred and One)
101
One Hundred and One
Program ended with exit code: 0