It is a very common use case where we want to return two values from a method, which can be either of the same data types or can be of different data types. Typically within this case, we would either create various 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 could create a struct 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 value(s) from a method. As great as that may sound consider this then if you have several methods which also return value(s) but each method returns the value(s) of different data types. I suppose in said case you could create a separate struct for each of the methods but it isn’t practical and comes on just terrible programming.
Got a Solution?
As the title of this article should have implied Swift has a type called Tuple which is used to group various values in a single compound value. Storing or returning two values of the same or different data types is child play for a tuple. here can or cannot be any relation between both the values.
Using Tuple
It is initialized in two ways:
- unnamed variables
- where the names are not defined within the tuple and use their position to access it
var tuple = ("football", "basketball") print(tuple.0) print(tuple.1)
- named variables
- where the names are defined within the tuple and use the names that were defined for them
var tuple = (atk : 2500, def : 2100) print(tuple.atk) print(tuple.def)