In this tutorial, we are going to see how can we leverage Tuples to return multiple return types from a function.
If you are not familiar with Tuples, head over to the below post to understand Tuples.
In Swift, we define a function as follows
This means that generally only type of data type can be returned through the function. Of course, we can use an Array or a Dictionary to return as many parameters of different types through this but that would be a little cumbersome process to go through if we need only two or three parameters.
Enter Tuples, let's say we need to split a full name into first name and second name. We just need to change the return type of function to a Tuple with two string parameters and we are done.
The Tuple has been made of optional type here just of because of type safety. If we pass a String with no spaces it will not return us anything.
Now let's call this function and use the values returned by it.
As you can see, not only this serves our purpose but also is a clean way to use the values returned by the function. Imagine having to use an Array and going through the safety checks and indexes just to use these two values.
Have something to add on? Spotted a mistake? Please feel free to comment down below.