Closures are self-contained blocks of code that can be passed around and used throughout our application. 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 this context, a closure can be thought of as a type that contains 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 them from functions.
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 Creating strong reference cycles with closures section of this chapter.
Closures in Swift are similar to blocks in Objective-C; however, closures in...