Tuples in Swift

In Swift, Tuples are another form of collection data type, that can store more than one value of different or same types.

What makes Tuples unique from Arrays is that Tuples can store values of different data types. An example of this could be the variable IDCard, which stores the name (String) of a student as well as his age (Int). In this tutorial, we will discuss the various types of tuples as well as some common functions.

Basic Syntax of a Tuple

The declaration of a tuple is exactly the same as creating a simple variable, except the two values are separated by a comma (,) as so:

var tupleName = (Value1, Value2, Value3… ValueX)
//Swift Tuple with the same Data type:
var characters = ("Harry", "Ron", "Draco")

//Swift Tuple with different data type:

var HealthID = ("Harry", 16, 175.4)

As shown, a tuple can have the same data type, as the names of book characters. But, it can also contain different data types like String(name), Int(age), and Height(Float) all within a single variable.

Accessing values of a Tuple

Accessing the values of a tuple is similar to accessing the values of Swift Array, by using the index number. The first variable value is marked with an index value of 0, the second value is 1, the third is 2, and so on.

Important Note: to find the “nth” value of a tuple, you need to use the index number “n-1.” Therefore, the index number when n=6 would be 5 i.e the index number of the 6th value is 5. We can access tuple values as so:

var healthID = ("Harry", 16, 175.4)

// Accessing the first element
print("Name:", healthID.0)

//Accessing the second element
print("Age:", healthID.1) 

//Accessing the third element print
print("Height:", healthID.2)
//Output:

Name: Harry
Age: 16
Height: 175.4

Modifying values of a Tuple

To modify, or change, the value of a tuple at a given index, we can simply assign the new value:

var healthID = ("Harry", 16, 175.4) 

print("Initial values: ")
print(healthID)

//Modifying the values: 
healthID.0 = "John"
healthID.1 = 21
healthID.2 = 182.6

print("New values: ") 
print(healthID)
//Output:

Inital values:
("Harry", 16, 175.4)
New values: 
("John", 21, 182.6)

As indicated by the output, we are able to change all the values inside our tuple.

Naming values of a Swift Tuple

Instead of referring to our values using an index number, alternatively, we can assign names to the values and access them accordingly. For example:

//Tuple with names
var iphone = (model: "13 pro max", storage: 128, cost: 1099.99)

//To access and print values
print("Model: ", iphone.model)
print("Storage: ", iphone.storage)
print("Cost: ",  iphone.cost)
//Output:

Model: 13 pro max
Storage: 128
Cost 1099.99

Assigning a value with a name is much easier to use rather than using its index, for advanced functions that use hundreds of parameters there is no way to recall the value at each index, instead of using names helps clearly distinguish and store the corresponding value as shown in the example above.

 

Nested Tuples

Similar to Nested Swift Functions, tuples in Swift can also be implemented as values inside other tuples. This can be shown as:

var companies = ("Apple", "Amazon", "Google", ("Whatsapp", "Facebook", "Instagram"))

In the example above, we created a parent tuple companiesconsisting of independent companies and as the fourth value, we pass a tuple of subsidiaries.  We can even access the values inside the tuple by:

var companies = ("Apple", "Amazon", "Google", ("Whatsapp", "Facebook", "Instagram")) 
//access and print the tuple variable
print(companies.3)

//accessing an value of the tuple
print(companies.3.2)
//Output:
("Whatsapp", "Facebook", "Instagram")
Instagram

As you can see, we are able to locate and print the third value from our nested tuple. Our first print statement simply prints the tuple as a whole, whereas the second print statement is directed to print the third value from the nested tuple.

We can apply the same concept to named nested tuples:

var companies = (company1: "Apple", company2: "Amazon", company3: "Google", subsidaries: (subsidary1: "Whatsapp", subsidary2: "Facebook", subsidary3: "Instagram"))

//access and print the tuple variable 
print(companies.company3)

//accessing an value of the tuple
print(companies.subsidaries.subsidary1)
//Output:
Google
Whatsapp

We were able to replicate the output by using the names instead of the index number, as indicated by the output.

Adding/Removing Values to Tuples

Currently, there is no shortcut function or method of adding or removing values to tuples. Unlike arrays, tuples cannot change their size, only replace their existing values. Running the following code:

var companies = ("Google","Apple")
company.remove("Apple")
company.add("Meta")
print(company)

Would throw an Exception Out-of-Scope error:

main.swift:6:1: error: cannot find 'company' in scope
company.remove("Apple") 
^~~~~~~
main.swift:7:1: error: cannot find 'company' in scope
company.add("Meta") 
^~~~~~~
main.swift:8:7: error: cannot find 'company' in scope
print(company)
      ^~~~~~~

Adding Values to Tuples through a Dictionary

One interesting method to add values to a tuple is by having a single variable as a Swift Dictionary and storing the various values within that dictionary. For example:

//Tuple consisting of dictionary of programming languages and the number their developers in millions

var mostUsedLanguage = (dataScience: ["Python": 4.3, "SQL": 2.4], webDesign: ["Javascript": 16.4, "HTML": 8.6])
print(mostUsedLanguage.0)

mostUsedLanguage.dataScience["Java"] = 3.7
print(mostUsedLanguage.0)
//Output

["Python": 4.3, "SQL": 2.4]
["Java": 3.7, "Python": 4.3, "SQL": 2.4]

By using this method, we can add values to tuples without having to face any errors. Although we could not append a tuple directly, a viable way around the current functionality constraints is to use either dictionaries or arrays to increase the content of tuples.

Leave a Reply

Your email address will not be published. Required fields are marked *