Swift Closures

Swift closures is an block of code statements, which are perform some special task. Closures are form of functions ,There are three type of Closures in Swift programming.

Global Function: This type of course are implemented by unique name (function name). That are defining statement and instructure which are execute when function are call. This are not capable to captured any values from containing context.

Nested Function: This type of closure are defined by a name and that is capable to capture properties of containing function.

Closure expressions : This type of closure is not define by name but that can capture the values from their containing context.

{(parameterLists) -> returnType in

For example

var myFactorial={(temp:Int)->Int in 
    var result=1
    var data:Int=temp
        return 1
    repeat {
        result = result * data
        data   = data-1
    } while data > 1
    return result



Inner function closures is capturing values for outer function. That is very interesting scenario. See this example

func update(_ data:Int)->()->Int{
    var temp=0
    let increment={ ()->Int in
        return temp
    return increment
var counter=update(2)

print(counter()) //2
print(counter()) //4
print(counter()) //8
print(counter()) //10
print(counter()) //12



In this example are first executed update(_:) function. that are accept one integer parameter value. And returning the reference of a inner closures. In this process counter are hold the reference of inner closure. and call counter() that are executed this closures. note that first call update function we are passing the data parameter value (2).

Note that closures are captured the variable data and temp update() function variable. when we are calling, then counter() function first time in this case add data + temp value and assigning to temp variable and returning this value by closures.

This is first execution of closure when we execute closure next time by using of counter(). Then temp value are not zero that value are updated by previous closure execution . That is advantage of inner closures.

Closures passing to function

func traceView(_ a:Int,_ closure: (Int) -> Void){
    print("traceView  a :\(a)")
    //execute closure

    print("traceView  a+9 :\(a+9)")

    //$0 is parameter  
    let check=$0+10
    print("Inside Closer : \(check)")



traceView  a :5
Inside Closer : 22
traceView  a+9 :14

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment

© 2021, kalkicode.com, All rights reserved