Swift – Functions and Closures ( Part 3 )

Functions

Methods in Swift is called as function and define by func keyword, after this keyword you should write the name of your function, parameters by their types and names in parentheses and lastly -> and the return type.

func function_name ( argument_name : argument_type , ... ) -> return type{
   //Your functions's code here..
}

 Functions can take a variable number of arguments and also return more than one value.

Lets write a function that calculates min, max, avarage and sum values of an array.

func  calculateStatisticsOfAnArray (array : [Float]) -> (min:Float, max:Float, sum:Float, avarage:Float){
    var min = array[0]
    var max = array[0]
    var sum : Float = 0
    var avarage : Float = 0
    
    for anItem in array{
        if anItem < min{             
            min = anItem         
        }else if anItem > max{
            max = anItem
        }
        sum += anItem
    }
    avarage = sum / Float (array.count)
    return (min, max,sum, avarage)
}

//Lets call our function to see statistics
let results = calculateStatisticsOfAnArray([5.0,6.7,8.9,3.4])
print("Min value : \(results.min) Max value : \(results.max) Sum :\(results.sum) Avarage : \(results.avarage)")

Here, the results:
Screen Shot 2016-01-30 at 20.39.43

Functions can be nested.

You can write a function inside of another function. A function can access the variable of the outer function. Generally, this usage is useful for making complex functions much more simpler and readable.

Screen Shot 2016-01-30 at 20.55.22

A function can return another function as its return value.

Functions are a first-class type. So, a function can return another function, as a return value, with its other return values.

As follows, makeMagnitudeValueFinder function defines that it will return a function that can get Double value and return its results as another Double value.

Screen Shot 2016-01-30 at 21.46.12

Functions can take another functions as their arguments.

Basically, If a function needs another function for its calculations or logical flow, it can simply take that function as an argument in Swift.

In following sample code, findSquentialMatchCasesInArray function uses matchCondition function, but it takes that function as an argument.

Screen Shot 2016-01-30 at 22.34.03.png

Closures

Closures are blocks of codes that can be called later. We can pair closures in Swift with block methods in Objective-C. You can write closures by surrounding your code with braces ({}) and in for separating your closure’s parameters with the body of your closure’s code.

numbers.map({
    (number: Int) -> Int in
    let result = 3 * number + 10 
    return result
})

See you in another chapter!
You can reach the full tutorial here!

Advertisements

One thought on “Swift – Functions and Closures ( Part 3 )

  1. […] Part 1 – Define variables, constants and simple object types – Swift Hello World! Part 2 – Use if, switch, for, for-in, while, repeat-while statements – Control Flows Part 3 – Functions & Closures – How to call and define them […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s