Pages

Function returning multiple values

If you have some experience in programming in any language like "C", "C++" etc you are well aware about that functions in these languages return only one value at a time, multiple returning values function are not allowed to use. But in Swift there is a little different theory about functions. In Swift language you can use "Nested functions" means function within a function as well as functions can "return multiple values" if you want them to return. Because Swift supports a concept of tuples so by using tuples a functions can return a tuple of values. Here is a good example ,through which I let you know how to make a function return multiple values, in which a function named "alplabetMaxMin()" will takes variable number arguments && then return two values maximum alphabet && minimum alphabet:

             //function taking variable number of arguments
func alphabetMinMax(characters: Character...) -> (Character, Character) {
             //characters variable is an array of characters
    var minChar = characters[0]
    var maxChar = characters[0]    
    for char in characters {        
        if char < minChar {
            minChar = char
        }
        if char > maxChar {            
            maxChar = char
        }
    }
            //returning two values as characters
    return (minChar,maxChar)

}

Here in this function we will pass any numbers of characters && function accepts them and stores them in an array of characters "characters" after processing it will return two values by calculating which one is maximum && which one is minimum. So now lets call this function:


var (a,b) = alphabetMinMax("z","c","g","e","u","p","d","h","l","s")
println(a)
println(b)

The output will be "c" && "z", where c is minimum && "z" is maximum character respectively. So this is how function using tuple concept can return multiple values.