Tuple in Swift
--
It is a very common use case where we want to return two values from a method, can be either of same data type or can be of different data types. What usually we do there is either create some local variables if the method is of the same class and set those variables from the method and consume them in the place where needed or we create a struct with just two variables and return that struct object from the method.
This post was originally posted at https://agrawalsuneet.github.io/blogs/tuple-in-swift/ and reposted on Medium on 21th May 2021.
This approach works fine but is it worth defining a new struct every time when we return two value from a method. What if we have several methods which return two values but each method returns the values of different data types? Are we going to create a separate struct for each method?
The answer is NO.
Swift provides us with a type called Tuple
which is used to group multiple values in a single compound value. Tuple is used to store or return two values of same or different data types. There can or cannot be any relation between both the values.
It can be initialised in two ways.
- Unnamed variables
- Named variables
And how do I use it?
It can be initialised in two ways.
- Unnamed variables
- Named variables
Unnamed variables Tuple
Unnamed variables Tuple is where we don’t define the names to the Tuple variables and while using them, we use their position to access it.
var tuple = ("Suneet", "Agrawal")print(tuple.0)
print(tuple.1)
Named variables Tuple
Named variables Tuple is where we define the names of the Tuple variables and while using them, we can use the same names with which we defined them with.
var tuple = (firstName : "Suneet", lastName : "Agrawal")print(tuple.firstName)
print(tuple.lastName)