Swift Tuples
In this article, we will explain Swift tuples.
Basics of Swift Tuples
A Swift tuple is a group of multiple values, enclosed in parentheses () and separated by commas, that can be treated as a single value.
The data types of tuple elements do not need to be the same.
var tuple1 = (5.0, "Test", 2, "ABC")
You can also assign names to each element, like this:
var expDate = (month: "February", year: 2025)
Unlike Arrays, tuples cannot have elements added or removed. The data types of the elements also cannot be changed.
They are useful when you want to return multiple values from a function without creating a struct or class.
Accessing Tuple Elements in Swift
You can access tuple elements in Swift using either an index or a name.
Indexes start at 0 and can be accessed using tuple.index notation.
var expDate = (month: "February", year: 2025)
print(expDate.0) // month
print(expDate.year)
The output is as follows:
February
2025
If you specify an index or name that does not exist, it will cause an error.
Modifying Tuple Elements in Swift
The elements of a Swift tuple can be modified by assigning a new tuple of the same data types.
You cannot assign only part of a tuple when updating it.
As long as the order and types of the elements match, the element names do not need to be specified.
Let’s update the values in the expDate tuple:
var expDate = (month: "February", year: 2025)
print(expDate)
expDate = (month: "May", year: 2026)
print(expDate)
expDate = ("July", 2027)
print(expDate)
The output is as follows, showing the tuple values being updated:
(month: "February", year: 2025)
(month: "May", year: 2026)
(month: "July", year: 2027)
That wraps up our explanation of Swift tuples.