Swift - Data Type Using Tuples

Introduction

A tuple is an ordered collection of values.

The values inside a tuple can be of any type.

They need not be all of the same type.

To store the coordinates of a point in the coordinate space:

var x = 7
var y = 8

This used two variables to store the x and y coordinates of a point.

You can store them together as a tuple instead of two individual integer variables:

var pt =  (7,8)

Here, pt is a tuple containing two values: 7 and 8. You can rewrite the tuple as follows:

Demo

var pt:  (Int, Int)
pt =  (7,8)
print(pt)

Result

Here, it is obvious that the pt is a tuple of type (Int, Int).

Here are some more examples of tuples:

Demo

var flight = (1001, "New York", "Seattle")
print(flight);//from w w w  . ja  va  2 s. c  o  m

var phone =  ("Jason", "001-222-3333")
print(phone)

Result

To retrieve the individual values inside a tuple, you can assign it to individual variables or constants:

Demo

var flight = (1001, "New York", "Seattle")
let (flightno, orig, dest) = flight
print(flightno)  /*w  ww  . j  a  va 2s .c o  m*/
print(orig)      
print(dest)

Result

If you are not interested in some values within the tuple, use the underscore _ character in place of variables or constants:

Demo

var flight = (1001, "New York", "Seattle")
let (flightno,  _ ,  _ ) = flight
print(flightno)

Result

Alternatively, you can access the individual values inside the tuple using the index, starting from 0:

Demo

var flight = (1001, "New York", "Seattle")
let (flightno,  _ ,  _ ) = flight
print(flight.0)  //7031
print(flight.1)  //ATL
print(flight.2)  //ORD

Result

Using the index to access the individual values inside a tuple is not intuitive.

A better way is to name the individual elements inside the tuple:

var flight = ( flightno :1001,  orig :"A",  dest :"B")

print(flight.flightno)
print(flight.orig)
print(flight.dest)

Once the individual elements are named, you can access them using those names:

Related Topic