Chapter 5. Closures and Operation Queues

The Swift language allows you to store code in variables. When you do this, the code is known as a closure, and Cocoa provides a number of tools that allow you to work with closures. One of the most important tools is called an operation queue, which lets you schedule closures to run in the future.

Closures allow code to do some very interesting things, including the following:

  • Provide code to a function that should be run when that function is complete, such as a download or a long-running computation
  • Enumerate over a collection of objects, and run some code on each one
  • Provide code for objects to call when they feel it’s necessary (e.g., event handlers)

Closures are discussed in detail in Functions and Closures. From a language perspective, they’re identical to functions—they take parameters and return values. From a code-writing perspective, the only real difference between functions and closures is that closures don’t have parameter names, while functions do.

To quickly refresh your memory, this is what closures look like:

let aClosure : Void -> Int = { return 1 }

aClosure() // returns 1

Because code can be divided up into chunks using closures, you can also give closures to the system for it to run. The mechanism that you use to do this is called operation queues, and they’re tremendously powerful tools for managing how the system does the work that you need to do.

Note

In Objective-C, closures are known as blocks. For this reason, several ...

Get Swift Development with Cocoa 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.