Nested Tuples
A tuple can be created as an element of another tuple in Swift. For example,
var names = ("X", "Y", "Z", ( "x", "y", "z") )
As the third element of the names tuple, we have a tuple ("x", "y", "z"). This is referred to as a nested tuple.
Example:
var names = ("X", "Y", "Z", ("x", "y", "z"))
// access first element
print(names.0) // prints "X"
// access the third element
print(names.3)
// access nested tuple
print(names.3.0) // prints "x"
Output:
Access Tuples value
There are two ways to access tuple values:
- Array-like access using the index number.
- Use the names or values label to access.
With examples, we'll learn how to access these tuples values in Swift.
Like an Array
Each tuple element is represented by index numbers (0, 1,...), similar to an array, with the first element at index 0.
To access tuple elements, we use the index number. For example,
// accessing the first element
course.0
// accessing second element
course.1
Using Name or Labels
We can also access the tuples using the given name or value labels. For example,
//accessing the course name
course.name
//accessing the course id
course.id
When we don’t specify our tuple’s name or label(unnamed tuples). for example,
let book = ( 30 , 10)
In this scenario, we can use index numbers to get access:
book.0 //30
book.1 //10
Use cases of Tuples
In a swift programming language, we may utilise tuples to group many values into a single compound value that we can use in applications based on our needs. Some of the use-cases of Tuples are as follows:
For returning multiple values
The most common use case for tuples is to return several values from a function. Here's an example:
Code
func getcourse() -> (name: String, week: Int){
let thecourse = "Swift"
let theweek = 8
return(thecourse, theweek)
}
print(getcourse())
Output
Tuples with Switch Case Statement
The switch statement in Swift allows us to compare a given value to many possible matching options and take the appropriate action.
Here is a simple example of using a tuple with a switch case expression in Swift programming language,
Code
let coordinates: (x: Int, y: Int, z: Int) = (1, 5, 0)
switch coordinates {
case (0, 0, 0):
print("Origin")
case (_, 2, 5):
print("On the x axis.")
case (1, _, 0):
print("On the y axis.")
case (1, 2, _):
print("On the z axis.")
default:
print("Somewhere in the space")
}
Output
Using switch statement with enum
In Swift, enumerations let us create a common type for a group of finite and related values.
Let's start with defining our first enum named Seasons:
enum seasons {
case spring
case summer
case rainy
case winter
}
Because the collection of declared values in an enum is finite, switching on the enum values rather than utilising numerous if-else statements is highly popular.
Here's an example of a switch statement in Swift that matches Operator enum values:
Code
enum seasons {
case spring
case summer
case rainy
case winter
}
let currentseason: seasons = .summer
switch currentseason {
case .spring:
print("Blossom by blossom the spring begins.")
case .summer:
print("It's so hot! Time for an Icecream.")
case .rainy:
print("It's raining. Bring an umbrella!")
case .winter:
print("It's cool out, wear a jacket!")
}
Output
Frequently Asked Questions
Which Version of Swift introduced Tuples?
Tuples are a new type in Swift 4 used to group many values into a single compound value. A tuple's values can be of any kind, and they don't have to be of the same type.
Is it possible to loop over a tuple in Swift?
Iterating over tuples is not presently supported in Swift. We can perform common sequence operations like indexing, slicing, concatenation, multiplication, and finding the minimum and maximum value on tuples.
In Swift, are tuples immutable?
Tuples are compound data types; declaring them as let makes them and their "members" immutable, whereas defining them as var makes them mutable.
Are Swift tuples ordered?
A tuple is a list of values sorted and separated by commas and enclosed in parentheses.
Conclusion
This article extensively discussed Swift Tuples, their types, how to access them, and their use cases, such as using tuples for returning multiple values and using tuples with switch case statements and examples. Check out the definitive swift tutorial for beginners to know more about Swift.
We hope this blog has helped you enhance your knowledge regarding tuples in Swift. You can learn more about IOS by visiting the Ios and os related articles in CodingNInjas Blogs.
Do upvote our blog to help other ninjas grow.
Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, interview bundle, follow guided paths for placement preparations, and much more!!
We wish you Good Luck! Keep coding and keep reading Ninja!!