Friday, August 5, 2016

Swift Tuple As Function Return Type

We need to go for Arrays or Dictionaries or our custom objects If our function has to return multiple values. Where as in Swift, we can use Tuple type as the return type If a function has to return multiple values. Tuple acts as one compound return value here.

Let me take an example where a function will take two integer values and returns the following,

  1. Two values are equal or not 
  2. Min value
  3. Max Value



   
func getMeBounds(first:Int, second:Int) -> (min:Int, max:Int, isEqual:Bool){
    
        if first > second{
            return (second,first,false);
        }
    
        else if first == second{
            return (first,first,true);
        }
    
        else{
            return (first,second,false);
         }
    
   }


Here is my Swift function 'getMeBounds' which takes two integer values and provides the results in a Tuple format.


   
(min:Int, max:Int, isEqual:Bool)


Let's see the calling and usage of this function which is returning a Tuple type.


  
let bounds = getMeBounds(18, second: 15)


Here bounds holds the Tuple type returned by 'getMeBounds' function.

We can easy check the conditions as shown below.


   
bounds.isEqual    // false
   bounds.min    // 15
   bounds.max    // 18


As simple as that. We don't need any Collection stuff here.



Hope this post is useful. Feel free to comment incase of any queries.