Writing completion blocks with closures in Swift

I never fully understood blocks until I learned how to write a method that took a block in as a parameter.

Even after I had a good handle on the concept of blocks, I still had to look up their syntax every time I wanted to write anything but the simplest of blocks (thank you fuckingblocksyntax.com). Swift’s version of blocks, known as closures, take a much cleaner, more natural approach to syntax. So without further ado, time to learn closures the way my dad taught me: by writing a completion block.

UIView’s animation API is one of the most common areas that iOS devs use blocks. Before blindly writing your own method, try using one of Apple’s code samples to familiarize yourself with the syntax. Below is an Objective-C example, and then the same code written in Swift:

Objective C:

    //setup a simple red view
UIView *redBox = [[UIView alloc] initWithFrame:CGRectMake(0,    0, 100, 100)];
    redBox.backgroundColor = [UIColor redColor];
    [self.view addSubview:redBox];
    [UIView animateWithDuration:1 animations:^{
        redBox.alpha = 0;
    } completion:^(BOOL finished) {
        NSLog(@"Red box has faded out");


let redBox = UIView(frame: CGRectMake(0, 0, 100, 100))
    redBox.backgroundColor = UIColor.redColor()
    UIView.animateWithDuration(1, animations:  {() in 
            redBox.alpha = 0
        }, completion:{(Bool)  in
            println("red box has faded out")

Much to the dismay of rabbits and near-sighted developers, carets ( ^ ) are nowhere to be found (yet) in Swift. Rest in peace old friend, you have been replaced by the keyword in. You use the keyword in once you have finished declaring the parameters and the return values for your closure. This will make more sense if I show you what autocomplete filled in once it knew what method I wanted:

UIView.animateWithDuration(duration: NSTimeInterval, 
    animations: (() -> Void)?, 
    completion: ((Bool) -> Void)?)

Focusing on this syntax, it becomes clear how to properly write the parameters and return values of a closure:

{(parameters) -> (return type) in expression statements}

In the Swift code example above, both of the animation closures returned void, so we could drop the return type syntax all together. That’s why you only see the ( ) for the parameters. Notice that even if there are no parameters, like in the first closure, you still need those empty ( ) before the keyword in. They are required. Bolded so you remember it.

Okay, now let’s try writing our own Swift method with a completion closure. In the Github repository linked at the bottom of this post, I have been working on a Github client app in Swift with a team of Code Fellows. In this project we have a network controller that handles all of the asynchronous network calls to Github’s API.

Let’s write a method that retrieves a list of users from a search query on the client. This method will need a completion closure to let the requesting View Controller know when the network call is finished, and provide an array of User models to populate our collection view.

Here’s what the signature of the function would look like:

func searchUsersWithSearchTerm(searchTerm: String, 
    completionClosure: (users :User[]) ->()) 

We have two parameters here: a string type called searchTerm and our completion closure. Notice the syntax in the closure parameter? First is the name of our closure, which is how we will call it later in the method, then the parameter (array of Users), followed by our return value (void). Below is an approximation of what the body of this method looks like:

    //setup a NSMutableRequest with the correct API URL and parameters
    //setup a dataTask on our NSURLSession instance

    //once our datatask has successfully retrieved the data we wanted,  and we have parsed through it to create an array of User Models, we call our completion closure like this:

    var users : User[] = //Parse the JSON data into Users

    completionClosure(users: users)

Calling our completion closure in Swift is almost the same way we call our completion block in Objective-C. It’s called just like any other function, and we make sure to pass in an array as a parameter, since that’s how we defined it up in our function signature. I purposely left out all the networking code to keep this post as short as I could, but feel free to check out the Github repository if you are interested in seeing how it works. We plan to have a blog post up on network in Swift in the near future.

Finally, lets take a look at how we would call this method from our SearchUsersViewController:

self.networkController!.searchUsers("Dr. Dre") { (users: User[]) in 
    self.searchUsers = users
    NSOperationQueue.mainQueue().addOperationWithBlock() { () in

One more thing I want to you notice is how I called addOperationWithBlock() on our mainQueue(). If a closure is the last parameter of a function’s signature, you can use special syntax to make it even more clean. This is referred to as a trailing closure. Trailing closures are written directly after the ( )'s of a function call. Below is a function call, first with a regular closure, then with a trailing closure.

//regular closure
doSomethingAwesome({ (isAwesome : Bool) in
    //inside our closure
//trailing closure
doSomethingAwesomer(){ (isAwesomer : Bool) in
    //inside our closure

It’s a subtle difference, and both ways work. Just remember that it has to be the last parameter of the function in order to use the trailing closure syntax.

Now you should know the basic syntax of closures in Swift. For some more advanced level stuff on closures, check out the Swift Programming Language on iBooks. It has an entire subsection on them. And here’s the link to the github client project.

There’s also already a Swift counterpart to fuckingblocksyntax.com called, you guessed it, fuckingclosuresyntax.com that is definitely worth adding to your bookmarks bar as you learn Swift.

Good day.

Ready to become a professional developer? Get in touch find out how!

Next PostPrevious Post

About the Author