6. Reusable Code: Closures

Closures in Swift have their own special syntax. When relating closures to Objective-C, you can think of closures as self-contained blocks of functionality. When you use them, you often directly replace an Objective-C block. You use them for things like creating a callback after a URL has been fetched from a server or calling a function when an animation is done. You use them for things like sorting when you need to pass a special sort function.

What Are Closures?

Closures are a familiar concept in many languages. Closures can be created when an environment is enclosed in a referencing unit of scope. We often say “a function within another function” when we’re talking about closures. But the real closure itself happens ...

Get Learning Swift 2 Programming, 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.