Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Tuples


Tuples groups multiple values into a single compound value. Unlike arrays and dictionaries, the values in a tuple do not have to be of the same type. The following example shows how to define a tuple:

var team = ("Boston", "Red Sox", 97, 65, 59.9)

In the preceding example, we created an unnamed tuple that contains two strings, two integers and one double. We can decompose the values from this tuple into a set of variables, as shown in the following example:

var team = ("Boston", "Red Sox", 97, 65, 59.9)
var (city, name, wins, loses, percent) = team

In the preceding code, the city variable will contain Boston, the name variable will contain Red Sox, the wins variable will contain 97, the loses variable will contain 65, and, finally, the percent variable will contain 0.599.

To avoid this decomposing step, we can create a named tuple. A named tuple associates a name (key) with each element of the tuple. The following example shows how to create a named tuple:

var team = (city:"Boston", name...