Swift Tuple

Tuples can hold zero or more values. The values need not be of the same type. Tuples in Swift are like mini Struct and should be used for storing temporary values only.


Tuples are handy when we have to return multiple values from a function.

Creating a Tuple

Values in a tuple are comma-separated as shown below.

var firstTuple = ("Balu Naik","balututorial.com")
print(firstTuple.0)
print(firstTuple.1)
print(type(of: firstTuple))

In order to define an empty tuple, you just need to do: var voidTuple = (). It has the type (void)

We can create tuples by defining the types as shown below:

var tuple : (Int, Bool) = (2,false)

Swift Tuple Element Names

We can name each element of the tuple similar to how parameters are named in Swift Functions

var namedTuple = (blogger: "Balu Naik",tutorial: "Swift Tuples", year : 2019)
print(namedTuple.blogger)
print(namedTuple.tutorial)
print(namedTuple.year)

The type of the above tuple is (String, String, Int).
  

Decomposing Swift Tuple

We can retrieve and set values from a tuple to variables and constants. This is known as decomposing tuples.

var (name, website) = firstTuple
let (b, t, y) = namedTuple
let(_ , websiteName) = firstTuple

(name, website) = ("Balu", "balututorial.com")

Swapping two elements using Swift Tuples

Provided they are of the same type, we can swap the values in two variables using a tuple

var i = 10
var j = 20
(i,j) = (j,i)
print("i is \(i) j is \(j)") //prints i is 20 j is 10

Swift Tuples are Value Types

Tuples in Swift are value types and not reference types.

var origin = (x: 0,y: 0,z: 0)
var newOrigin:(Int,Int,Int) = origin

newOrigin.0 = 1
newOrigin.1 = 5
newOrigin.2 = 10

print(origin) // "(x: 0, y: 0, z: 0)\n"
print(newOrigin) // "(1, 5, 10)\n"

As it is evident from the above example, values changed in the new tuple have no impact over the earlier one from which they were copied.

[quote]Note: Values present in a let tuple cannot be modified.[/quote]

Swift Tuple inside another tuple

Tuples is compound types. One Tuple can be nested inside another.

var nestedTuple = (("Swift","Swift tuples tutorial"),("Android","Android Volley Tutorial"))
nestedTuple.0.1 //Swift tuples tutorial

Returning Multiple Values From a Function

Using Swift tuple we can return multiple values from a function as shown below.

func sumOfTwo(first a: Int, second b: Int) -> (Int,Int,Int) {


    return(a,b,a+b)
}
var returnedTuple = sumOfTwo(first: 2, second: 3)
returnedTuple.2 //5

To set the element names in the returned tuple, we need to explicitly set them in the tuple type definition itself.

var returnedTuple : (first: Int, second: Int, sum: Int) = sumOfTwo(first: 2, second: 3)
print(returnedTuple.first) //3
print(returnedTuple.second) //3
print(returnedTuple.sum) //5

One Response