Don’t Panic! Create your own @escaping completion handler in Swift

December 27, 2018

(Full source code for this post: https://github.com/joshbuddha/completionHandler.git)

Lets go beyond simply using a completion handler.

In this post we will create our own completion handler. Along the way we’ll learn about closures, the @escaping keyword, typealias, and the capture list.

A completion handler relies on closures. Apple defines them like this: “Closures are self-contained blocks of functionality that can be passed around and used in your code.

We are essentially defining functionality that will be passed to something that takes time so that it can be executed when that thing has completed its work. In our case we are telling the space ship where we want to go and then getting the details about our destination once we arrive.

Its time to help our hero Arthur travel the universe and keep his anxiety under control.

1. Define a typealias for the closure.

This structure accepts one HeartOfGold enum and returns nothing or Void.

2. Define the HeartOfGold enum.

Once the work has been completed the HeartOfGold enum will be sent. It defines the ship destinations and 2 nested enums that define inventory and anxiety level.

Ok, now its time for Arthur to decide where he wants to go. The following passes the number associated with the destination as well as the closure block that will be executed upon arrival. Also note the capture list where [unowned self] is set. We used unowned or weak in this case to avoid retain cycles.

Now lets look at the method that does all the work that takes time. The following accepts the location integer as well as the closure we defined earlier. Once the work is done the completion closure will be called:

The @escaping attribute is required because the HeartCompletion closure is invoked AFTER the function has completed the work.

Here is the entire class:

Again, the full source code is here: https://github.com/joshbuddha/completionHandler.git Hit me up in the comments with any questions.

Josh K

Leave a Comment