Callbacks, as mentioned, allow us to handle asynchronous operations by specifying what should happen when that operation is completed. Simply put, a callback is any piece of executable code that is passed to a function that will call it at some later point, eithersynchronously or asynchronously. As an example of synchronous callback, in Chapter 3, Diving into Foundation and the Standard Library we used the forEach
method available on Array
objects:
// Using forEach with a closure: (1...5).forEach { value in print("\(value)") }
This could be equivalently rewritten as follows, where we replace the closure with a function:
// The above is equivalente to this: func printValue<T>(val : T) { print("\(val)") } (1...5).forEach(printValue)
These two examples should help clarify that callbacks and closures correspond to different concepts, although with some overlap, since closures can be used to implement callbacks.
Closures, also known as lambdas in functional languages...