Using functions that take in and execute closures can be extremely useful for sending a block of code to be executed elsewhere. We can start by allowing our function to take in an optional closure that will (in this case) return Void
.
func closedFunc(block: (()->Void)? = nil) {
print("Just beginning")
if let block = block {
block()
}
}
Now that our function has been defined, let's call it and pass in some code:
closedFunc() { Void in
print("Over already")
}
By using a trailing closure with our function call, we can pass in code (in this case, print
) to be executed at some point within our closedFunc()
function.
The log should print:
Just beginning
Over already
A more specific use case of this could include the execution of code between two classes:
class ViewController: UIViewController {
override func viewDidLoad() {
let _ = A.init(){Void in self.action(2)}
}
func action(i: Int) {
print(i)
}
}
class A: NSObject {
var closure : ()?
init(closure: (()->Void)? = nil) {
// Notice how this is executed before the closure
print("1")
// Make sure closure isn't nil
self.closure = closure?()
}
}
The log should print:
1
2