What is a Tuple in Swift?
When and Where use Tuple in Swift?
A Tuple is a comma-separated list of types, enclosed in parentheses and commonly used to return multiple values from a function call. In Swift, a tuple can consist of multiple different data types. They are an ordered list of elements and provide a way to group multiple values together. Tuples are defined using ()
.
// Basic syntax of tuple
let laptop = ("MacBook", 999.99)
let point = (x: 10, y: 10)
Empty tuple
()
is the empty tuple – it has no elements and also represents the Void
type. We can define an empty tuple, but the compiler will show a warning message.
let emptyTuple = ()
Unnamed Tuple
Unnamed Tuple is where we don’t define the names to the Tuple variables and when using them we use their position to access it.
let coordinates = (54.2667, 8.4833) // Unnamed Tuple
We can access the inner values using the dot(.
) notation followed by the index of the value.
let person = ("Paul", 30) // Unnamed Tuple
print("\(person.0) age is \(person.1)")
The elements of a tuple are similar to of an array and represented by index numbers. The first element is at index
0
and the second element is at index1
. The indexing continues in this order.
Named tuple
Named tuples are used to group multiple values into a single by using parentheses and need to define those values with named variables and those are separated by commas. An element name consists of an identifier followed immediately by a colon (:).
let coordinates = (lat: 52.0367, lon: 5.5730) // named tuple
There are two ways of accessing the data in a named tuple: by position or by name. That means tuples can be accessed using element names (“lat” and “lon” below), or using a position in the tuple, e.g. 0 and 1
print(coordinates.lat, coordinates.lon) // by name
print(coordinates.0, coordinates.1) // by position
It is the good practice to use the named tuples as it makes code more readable.
Nested tuple
Tuples created as an element of another tuple are called Nested Tuples.
let userInfo = ("Julia", 34, ("USA", "New York", 10001))
print(userInfo.0, userInfo.1, userInfo.2.0, userInfo.2.1, userInfo.2.2)
// Julia 34 USA New York 10001
Creating and accessing nested tuples can be complicated, instead of it, we can create our own struct and return the object of it.
Tuple as a Type alias
Tuple with a type alias will give more readability to our code and also prevent the duplicate code lines.
typealias PersonTuple = (String, Int)
func getPerson() -> PersonTuple {
return ("Mike", 45)
}
print(getPerson().0) // Mike
Tuple for Returned Function Values
In Swift, we can return multiple values from a function if we set the return type to a tuple.
func getPersonDetail() -> (String, Int, String) {
return ("Mike", 45, "New York USA, 10001")
}
Multiple assignments
We can use tuples to initialize more than one variable on a single line:
var (student, age, course) = ("Sam", 20, "Computer Science")
Modify Tuple Element
To modify, or change, the value of a tuple at a given index, we can simply assign the new value:
var book = ("Harry Potter - Chamber of Secrets ", 300)
print("Original Tuple: Book name \(book.0) and pages are \(book.1)")
// modify second value (page count)
book.1 = 251
print("After Modification: Book name \(book.0) and pages are \(book.1)")
Adding-Removing Elements from Tuple
We cannot add or remove elements from a tuple in Swift. Unlike arrays, tuples cannot change their size, only replace their existing values.
When we try to add and remove elements from the tuple, we get compile time errors.
Adding Values to Tuples from a Dictionary
As we know we can add elements to a dictionary, to add values to a tuple is by having a single variable as a Swift dictionary and storing the various values within that dictionary.
var langauge = (iOS: ["Swift": 4.3, "Objective C": 2.0], android: ["Java": 19.0])
print(langauge.0) // ["Swift": 4.3, "Objective C": 2.0]
langauge.iOS["Swift"] = 5.7
langauge.android["Kotlin"] = 1.7
print(langauge.0) // ["Swift": 5.7, "Objective C": 2.0]
print(langauge.1) // ["Java": 19.0, "Kotlin": 1.7]
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.
Tuples for iterating a dictionary
We can also get tuples when iterating a dictionary to get both key and value.
var langauge = ["Swift": 5.7, "Objective C": 2.0, "Java": 19.0, "Kotlin" : 1.7]
for (key, value) in langauge { // (key, value) is tuple
print("\(key) current version is - \(value)")
}
Tuples don’t conform to the hashable protocol. Hence it cannot be used as dictionary keys.
Decomposing Tuples
We can decompose a tuple into its parts using the assignment operator.
var response = (code: 502, message: "Bad Gateway")
let (responseCode, responseMessage) = response // Decomposing Tuples
print(responseCode, responseMessage) // 502 Bad Gateway
If we only need some of the tuple’s values in the code, we can use underscore (_
) for other parts of the tuple to ignore when we decompose the tuple.
var response = (code: 502, message: "Bad Gateway")
let (_, responseMessage) = response
print(responseMessage) // Bad Gateway
👉 Tuples are value types. When we initialize a variable tuple with another one it will create a copy.
var product = (phone: "iPhone", model: "12")
var item = product
product.phone = "Android"
product.model = "Samsung s22"
print(item) // (phone: "iPhone", model: "12")
print(product) // (phone: "Android", model: "Samsung s22")
We can see in the above code product is a tuple and then assign another variable item. Then change the first created tuple values, we can see the second variable(item) values not changed.
A tuple can have any number of items and they can be of different types (integer, float, string, array, dict etc.)
👉 We can count the number of elements in a tuple like this:
let tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9 , 10 , 11 , 12 , 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 , 25, 26, 27, 28, 29, 30)
let tupleSize = Mirror(reflecting: tuple).children.count
print(tupleSize)
Conclusion
Tuples provide a way to group multiple values together representing them as single compound values. The best use case of a tuple in Swift would be when we want a function that can return multiple types.
Thanks for reading. If you have any comments, questions, or recommendations feel free to post them in the comment section below! 👇.
Please share and give claps 👏👏 if you liked this post.