4. Closures and Functions

Lexical closures provide the basis for methods, functions, and “block” parameters, all of which power the Swift applications you develop. By encapsulating state and functionality, they promote behavior to first-class constructs. Closures enable you to pass functionality as parameters and to treat actions as variables, ready for later execution and repeat use. If you’re entering Swift from other languages, you might already know these features as lambdas, blocks, or anonymous functions. This chapter explores closures, showing how they work in Swift and how to best incorporate them into your applications.

Building a Function

When I first started learning Swift, I decided to see how many ways I could rewrite one basic ...

Get The Swift™ Developer’s Cookbook 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.