user6847532
user6847532

Reputation:

How does a trailing closure work?

I read this one but did not get anything understandable for me. But I understand this closures syntax:

var cal = {(num1: Int)-> Int in
    return num1 * 2;
}

var clusers = [cal,
               {(num1:Int) -> Int in return num1 * 3},
               {(num1:Int) -> Int in num1 * 4},
               {(num1:Int) in num1 * 5},
               { num1 in num1 * 6},
               { $0 * 7}]
for cluser in clusers{
    cluser(100)
}

How can I make a trailing closure ?

Basically here is a trailing closure. I am unable to understand that:

  //call dispatch async to send a closure to download queue
  dispatch_async(download) { () ->Void in

    //some code goes here          
  }

Upvotes: 0

Views: 150

Answers (1)

user4527951
user4527951

Reputation:

Let this is my function

func someFunctionThatTakesAClosure(index: Int, closure: () -> Void) {

}

If you need to pass a closure to the above function you write something like below

someFunctionThatTakesAClosure(5, closure: {
   // code included in closure
})

But if closure is the last argument passed to the function, as in the above function we can write above piece of code like this also

someFunctionThatTakesAClosure(5) { 
   // code included in closure
}

That is why it is called trailing closure.

Upvotes: 1

Related Questions