Member-only story
Hi everyone, welcome back. Today, we will be going over tuples in Swift. Tuples are objects that are capable of storing multiple items within a single variable. Tuples are a built in data type within Swift and are immutable, meaning once they are created, they cannot be modified. With this introduction out of the way, let’s get into it.
Tuples
We can create an empty tuple by using parenthesis:
let tuple = ()
We use the let keyword in Swift to create a constant as tuples are immutable. We can create a populated tuple by adding in values within the parenthesis:
let tuple = (1, 2, 3)
As we can see in the above example, we added 3 integers into our tuple. Each integer, or item added into a tuple, is separated by a comma. Let’s print our tuple to see what it looks like:
let tuple = (1, 2, 3)
print(tuple)Output:
(1, 2, 3)
Different Data Types
The tuple in Swift can support multiple data types, meaning that the data types of items within the same tuple can be different. Let’s see an example:
let tuple = (16, "string", false)
print(tuple)Output:
(16, "string", false)