Tuple in Swift

Suneet Agrawal
2 min readMay 21, 2021

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.

  1. Unnamed variables
  2. Named variables

And how do I use it?

It can be initialised in two ways.

  1. Unnamed variables
  2. 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)

Please continue reading at https://agrawalsuneet.github.io/blogs/tuple-in-swift/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--