Introducing closures
Closures are self-contained blocks of code that can be passed around and used throughout your application code. We can think of an int type as a type that stores an integer and a string type as a type that stores a string. In that context, a closure can be thought of as a type that holds a block of code. What this means is that we can assign closures to a variable, pass them as arguments to functions, and also return functions from them.
Closures have the ability to capture and store references to any variable or constant from the context in which they were defined. This is known as closing over the variables or constants, and the best thing is, for the most part, Swift will handle the memory management for us. The only exception is when we create a strong reference cycle and we will look at how to resolve this in the Strong reference cycles with closures section of this chapter.
Closures in Swift are similar to blocks in Objective-C; however, closures in Swift are a lot...