Make Swift 3 closures your friend

[Download Xcode project with all source code from GitHub to follow along.]

Today, we’ll finish our discussion of the benefits of using Objective-C blocks and Swift closures by writing code to define and use a closure in Swift 3. For the full background on this topic, please read my last post entitled “Make blocks (closures) your friend (Objective-C and Swift 3).” Let’s plunge into Swift 3:

1) Let’s define a type (typealias) for the closure. We want to be able to easily pass the closure as a function argument:

2) Now we define the closure, encoding what we want it to do, and pass it as an argument to a method:


3) When our background task for downloading an image completes, it calls our closure (completion handler) to inform the caller of success or failure and updates the user interface (UI) on the main thread:

Note that the “completionHanlder” argument is marked as “@escaping.” Apple defines an “escaping closure” thusly:


A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter’s type to indicate that the closure is allowed to escape.

One way that a closure can escape is by being stored in a variable that is defined outside the function. As an example, many functions that start an asynchronous operation take a closure argument as a completion handler. The function returns after it starts the operation, but the closure isn’t called until the operation is completed—the closure needs to escape, to be called later.

So there you have it. We’ve learned about, formally defined, reviewed some code for, and written some code for blocks in Objective-C, and written some code for closures in Swift. Remember that blocks are one of the most important programming language constructs you’ll ever learn about. Please leave a comment if you have questions or feedback.

[Download Xcode project with all source code from GitHub to follow along.]


Author: Andrew Jaffee

Avid and well-published author, software engineer, designer, and developer, now specializing in iOS mobile app development in Objective-C and Swift, but with a strong background in C#, C++, .NET, JavaScript, HTML, CSS, jQuery, SQL Server, MySQL, Oracle, Agile, Test Driven Development, Git, Continuous Integration, Responsive Web Design, blah, blah, blah ... Did I miss any fad-based catch phrases? My brain avatar was kindly provided by under a Creative Commons Attribution-NoDerivs 3.0 Unported license.

Leave a Reply

Your email address will not be published. Required fields are marked *