0

I am new to swift programing development. I want to know to how to pass a closure to another closure.

Is there any difference between closure in swift and blocks in objective.

Raj Aggrawal
  • 761
  • 1
  • 6
  • 21
  • You may declare variable of function type and do with this variable whatever you want. – Yury Jul 07 '16 at 09:50
  • Closure is replacement to the blocks, it is not exactly same. You can refer this answer http://stackoverflow.com/questions/33591777/nested-closures-in-swift-2-1 – Rohit Pradhan Jul 07 '16 at 09:54

1 Answers1

2

How to pass a closure to a closure?

A closure can be seen as just any other (non-closure) type. This means you can construct a closure where the argument of the closure describes another closure type.

E.g.

let sendMeAClosure: ((Int) -> String) -> () = {
    print($0(42)) /* ^^^^^^^^^^^^^^^- argument of sendMeAClosure
                                      is a closure itself        */
}

let myClosure: (Int) -> String = {
    return "The answer is \($0)."
}

sendMeAClosure(myClosure) // The answer is 42

Note that functions in Swift are just a special type of closure, so you might as well supply a function reference (which has a signature matching the argument type) to sendMeAClosure above.

/* sendMeAClosure as above */

func myFunc(arg: Int) -> String {
    return "The answer is \(arg)."
}

sendMeAClosure(myFunc) // The answer is 42

Is there any difference between closure in swift and blocks in objective?

For your 2nd question, refer to the following Q&A

Community
  • 1
  • 1
dfrib
  • 70,367
  • 12
  • 127
  • 192