Closures
Closures are great tools for FP as they are functions without the func
keyword and name. Like functions, closures are self-contained blocks of code that provide a specific functionality and can be stored, passed around, and used in the code. Closures capture the constants and variables of the context in which they are defined. Although closures are the equivalent of blocks in Objective-C, they have a simpler syntax in Swift compared to the C and Objective-C block syntax. Nested functions, which we have covered in a previous section, are special cases of closures. Closures are reference types that can be stored as variables, constants, and type aliases. They can be passed to and returned from functions.
Closure syntax
A general closure syntax is as follows:
{ (parameters) -> ReturnType in // body of closure }
A closure definition starts with {
, then we define the closure type, and finally we use the in
keyword to separate the closure definition from its implementation.
After the in...