Reputation: 761
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
Reputation: 73186
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
For your 2nd question, refer to the following Q&A
Upvotes: 2