Friday, 1 April 2016

Function in Swift

Functions are a self contained block of code that perform a specific task. Every function has a type in swift(parameter type and return type). Swift functions are more flexible  and allow us to do more things with it. As with swift function we can return multiple values as tuple, can pass variable number of arguments to it. It also allows the nesting of the function .
All of these we will look in  below described example:


func doSum(numbers:[Int])-> Int{

var sum =0
for num in numbers {
sum =  sum+ num
}

return sum
}


This function named doSum takes an integer array and do the sum of the numbers and in last return the sum.

To return multiple values from function use:

func doMath(numbers:[Int])-> (sum:Int, min:Int, max:Int){

var sum =0
var max = numbers[0]
var min = numbers[0]
for num in numbers {
         sum =  sum+ num
       
         if num >max{
              max  = num
        } else if num< min{
             min = num
       }
}

return (sum,min,max)
}

To call this function

let result =  doMath([23,34,56,56,67])

print(result.max)
print(result.min)
print(result.sum)

Functions can take variable number of argument , collecting them in array :

func doAvg(numbers:Int...)-> Int {

var sum =0
for num in numbers {
 sum = sum+ num
}
return sum/ numbers.count
}

To call this function
 let average = doAvg(23, 34, 5,55)


Function can also  be nested. In this case the inner function  will have access to the variable and things of the outer function .


Reference: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html