Chapter 9
Closures
Closures are blocks of code that perform specific tasks; they can be passed around in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in some languages. Closures can capture and store references to constants and variables in the context in which they are defined. This is called “closing over” these constants and variables. Swift handles all the memory management required for capturing the environment.
The definition for closures is similar to that for functions, because in Swift functions are a special case of closures, with some differences:
- Global functions are closures that have a name and don’t capture any values.
- Nested functions are closures that have a name but only capture ...
Get Learn Swift 2 on the Mac, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.