An introduction to closures
Closures are self-contained blocks of code that can be passed around and used throughout our application. We can think of the Int
type as a type that contains an integer, and the String
type as a type that contains a string. In this context, a closure can be thought of as a type that contains a block of code. This means that we can assign closures to a variable, pass them as arguments to functions, and return them from a function.
Closures can 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, for the most part, Swift will handle the memory management for us. The only exception is in creating a strong reference cycle, and we will look at how to resolve this in the Creating strong reference cycles with closures section of Chapter 18, Memory Management.
Closures in Swift are similar to blocks in Objective-C; however, closures in Swift are...