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 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.
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)
To define the type of Tuple we can simply use brackets ()
and define the type inside it.
var tuple : (String, Int)
func getEmployeeDetails() -> (String, Int) {
return (name : "Suneet Agrawal", employeeId : 100)
}
What if I want to return three values from a method?
There is no direct way or type defined in Swift but as a work around we can put a Tuple inside another Tuple but keep in mind it might overcomplicate your code so use it wisely.
var tuple = (name : (firstName: "Suneet", lastName : "Agrawal"), employeeId : 100)
print(tuple.name.firstName)
print(tuple.name.lastName)
print(tuple.employeeId)
Last Question. What if I want to return four or more values?
You can put as many Tuple inside each other as you want but now you are getting greedy. I’ll suggest to create your own struct and return the object of it.