Chapter 5. Closures: Fancy, Flexible Functions

image

Functions are useful, but sometimes you need more flexibility. Swift allows you to use a function as a type, just like an integer or string. This means you can create a function and assign it to a variable. Once it’s assigned to a variable, you can call the function using the variable, or pass the function to other functions as a parameter. When you create and use a function in this manner, it’s called a closure. Closures are useful because they can capture references to constants and variables from the context in which they are defined. This is called closing over a value, hence the name.

Meet the humble closure

This is a closure:

image

You can call pizzaCooked() just like a regular function:

image

At first glance, you might think a closure is just another way to write a function.

You’d be kind of correct, but closures allow you to do a lot of things that functions alone aren’t suited for. You’ll understand the power in a few pages.

Closures are like functions that you can pass around as variables. That’s the starting point to their usefulness, and it only goes up from there!

Closures are definitely a little bit confusing.

It’s normal ...

Get Head First Swift 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.