Tuples

Tuples group 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. While tuples are included in this chapter about collections, they actually behave more like a custom type than a collection.

The following example shows how to define a tuple:

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

In the preceding example, an unnamed tuple was created that contains two strings, two integers, and one double. The values of the tuple can be decomposed 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.

The values of the tuple can be retrieved by specifying the location of the value. The following example shows how we can retrieve values by their location:

var team = ("Boston", "Red Sox", 97, 65, 59.9)  
var city = team.0 
var name = team.1  
var wins = team.2  
var loses = team.3  
var percent = team.4 

Naming tuples, known as named tuples, allows us to avoid the decomposition step. 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:"Red Sox", wins:97, loses:65, percent:59.9) 

Values from a named tuple can be accessed using the dot syntax. In the preceding code, we will access the city element of the tuple like this: team.city. In the preceding code, the team.city element will contain Boston.

Tuples are incredibly useful, and can be used for all sorts of purposes. I have found that they are very useful for replacing classes and structures that are designed to simply store data and do not contain any methods. We will learn more about classes and structures in Chapter 5, Classes and Structures.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset