Header Logo

Swift: Completion Handlers

One of the things you’ll quickly find when you first start writing code is that things need to happen in a very specific order. Completion handlers (aka completion blocks, call backs, call back blocks) are little lines of magic code that will let you order things correctly.

May 29, 2017-2 min read

For when doing things in perfect order is important

One of the things you’ll quickly find when you first start writing code is that things need to happen in a very specific order. Completion handlers (aka completion blocks, call backs, call back blocks) are little lines of magic code that will let you order things correctly.

func thisNeedsToFinishBeforeWeCanDoTheNextStep(completion: () -> ()) {
    print("The quick brown fox")
    completion()
}
func thisFunctionNeedsToExecuteSecond() {
   print("jumped over the lazy dog")
}

We now have our two functions defined. Notice how the first function has the word completion with two sets of parentheses. That is how we write a basic completion handler.

Now, in order for the sentence we’re trying to print to make sense thisNeedsToFinishBeforeWeCanDoTheNextStep must execute first and thisFunctionNeedsToExecuteSecond must execute second. To make sure they execute in that exact order we just do this:

thisNeedsToFinishBeforeWeCanDoTheNextStep { () -> () in

    thisFunctionNeedsToExecuteSecond()

}

Bing, bang, boom, we’re done. Now those two functions will absolutely run in the correct order.

You can write completion handlers a couple of different ways. This is another very common way to write the syntax:

func thisNeedsToFinishBeforeWeCanDoTheNextStep(completion: () -> Void) {

    print("The quick brown fox")

    completion()

}

It does the exact same thing.

If you need to pass along any information out of a function that has a completion handler this is all you have to do:

func thisNeedsToFinishBeforeWeCanDoTheNextStep(completion: (String) -> ()) {

    let stringToPassOutOfTheCompletionHandler = "The quick brown fox"

    completion(stringToPassOutOfTheCompletionHandler)

}

Now when you call that function it will look like this:

thisNeedsToFinishBeforeWeCanDoTheNextStep { (stringToPass) -> () in

    let firstPartOfTheSentence = stringToPass

    print(firstPartOfTheSentence)

    thisFunctionNeedsToExecuteSecond()

}

After it’s completed it’s task it will hand off stringToPass. Once again, bing, bang, boom. You get the sentence printed in the correct order.

*Note: You can name stringToPass anything you want when you call thisNeedsToFinishBeforeWeCanDoTheNextStep .

This is the basics of completion handlers. As you get more and more comfortable you’ll learn how to string together complex functions that will guarantee that the right information is in the right place at the right time.

If you find a no-frills Swift tutorial helpful hit the heart down below. Cheers!



© 2019 Phil Andrews