Chapter 5. Closures: Fancy, Flexible Functions
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:
You can call pizzaCooked() just like a regular function:
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access