Tuple in Swift

This article explains what a Tuple is and when and where it is used. Happy reading!!!

4 min readMay 15, 2017
pic credit: Stocksnap.io

Tuple is a group of different values represented as one . According to apple, a tuple type is a comma-separated list of zero or more types, enclosed in parentheses. It’s a miniature version of a struct.

Let’s consider an example: A name say John smith can be declared as a tuple like ("John", "Smith") . It holds the first and last name of a person. You can access the inner values using the dot(.) notation followed by the index of the value:

var person = ("John", "Smith")

var firstName = person.0 // John
var lastName = person.1 // Smith

The type of a tuple is determined by the values it has. So ("tuple", 1, true) will be of type (String, Int, Bool).

() is the empty tuple – it has no elements. It also represents the Void type.

Tuples don’t conform to the hashable protocol. Hence it cannot be used as dictionary keys.

Creating a tuple:

You can declare a tuple like any other variable or constant. To initialize it you will need a another tuple or a tuple literal. A tuple literal is a list of values separated by commas between a pair of parentheses. You can use the dot notation to change the values from a tuple if it’s declared as a variable.

var point = (0, 0)

point.0 = 10
point.1 = 15

point // (10, 15)

Note: Tuple are value types. When you initialize a variable tuple with another one it will actually create a copy.

var origin = (x: 0, y: 0)

var point = origin
point.x = 3
point.y = 5

print(origin) // (0, 0)
print(point) // (3, 5)

Named elements:

You can name the elements from a tuple and use those names to refer to them. An element name is an identifier followed by a colon(:).

var person = (firstName: "John", lastName: "Smith")var firstName = person.firstName // John
var lastName = person.lastName // Smith

Multiple assignment:

You can use tuples to initialize more than one variable on a single line:

var (a, b, c) = (1, 2, 3)

Returning multiple values:

You can return multiple values from a function if you set the result type to a tuple.

Please note that tuples are passed by value, not reference.

In the above code, for code readability, I’ve used a typealias to pre-define the tuple’s structure.

Tuples for iterating a dictionary getting both key and value:

for (key,value) in myDictionary {  println("My key is \(key) and it has a value of \(value)")}

In the above iteration through dictionary example, if we need only the key , then you can use “_” to ignore the value for key.

Note: the _ means “I don’t care about that value”

for (key,_) in myDictionary {println("My key is \(key)")

Decomposing Tuples:

let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")

You can decompose a tuple’s contents into separate constants or variables, which you then access as usual:

let (statusCode, statusMessage) = http404Errorprint("The status code is \(statusCode)")// Prints "The status code is 404"print("The status message is \(statusMessage)")// Prints "The status message is Not Found"

If you only need some of the tuple’s values, ignore parts of the tuple with an underscore (_) when you decompose the tuple:

let (justTheStatusCode, _) = http404Errorprint("The status code is \(justTheStatusCode)")// Prints "The status code is 404"

Alternatively, access the individual element values in a tuple using index numbers starting at zero:

print("The status code is \(http404Error.0)")// Prints "The status code is 404"print("The status message is \(http404Error.1)")// Prints "The status message is Not Found"

You can name the individual elements in a tuple when the tuple is defined:

let http200Status = (statusCode: 200, description: "OK")

A tuple inside another tuple:

we’re gonna mix it up by creating tuple which contains another tuple.

let bar: (Int, (Bool, String)) = (1, (false, "Hello"))print(bar.0) // print: “1”print(bar.1.0) // print: “false”print(bar.1.1) // print: “Hello”

An easy way of swapping two values:

var a = 5 
var b = 4
(b, a) = (a, b)

Where to use tuples

The best place to use a tuple would be when you want a function that can return multiple types. If you’re an Objective-C developer, this concept sounds impossible unless you use an array or dictionary. Previously we’ve had to overcome such problem by either return an NSArray or NSDictionary.

Sources: Medium article, Weheartswift.

That’s it. !


If you enjoyed reading this post, please share and give some clapps so others can find it 👏👏👏👏👏 !!!!

You can follow me on Medium for fresh articles. Also, connect with me on LinkedIn.

If you have any comment, question, or recommendation, feel free to post them in the comment section below!