Raj Aggrawal
Raj Aggrawal

Reputation: 761

Passing closure to another closure

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.

Upvotes: 0

Views: 189

Answers (1)

dfrib
dfrib

Reputation: 73186

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

Upvotes: 2

Related Questions