Completion Handlers

Introduction

Welcome to the last lesson of Intro to Functional Swift. If you’ve done any API calls, such as Facebook Login, you used completion handler blocks. Today, you will learn why we use them and how to design one like a pro.

Problem

I’ve heard about it. I don’t know how to make one

Definition

Do something when something has been done

Usage

  1. Notify the user when the download completed
  2. Animation

Design Handler Block

Create a closure which will be called within a function.

  1. let handlerBlock: (Bool) -> () = {
  2. if $0 {
  3. print("Download Completed")
  4. }
  5. }
  6. let myHandlerBlock: (Bool) -> () = { (isSuccess: Bool) in
  7. if isSuccess {
  8. print("Download has been finished")
  9. }
  10. }
  11. myHandlerBlock(true) // "Download has been finished"

Design Function

Create a function that is similar to downloading an image by calling a for-in loop. Once the download has been finished, you may notify the user.

  1. func downloanAnImage(completionBlock: (Bool) -> Void) {
  2. for _ in 1...10000 {
  3. print("Downloading")
  4. }
  5. completionBlock(true)
  6. }

The function above takes a parameter whose type is (Bool) -> Void. You will pass myHandlerBlock.

  1. downloanAnImage(completionBlock: myHandlerBlock)
  2. // 1
  3. // 2
  4. // ...
  5. // 10000
  6. // "Download has been finished"

Pass Closure Directly

You may pass a closure block directly when you execute the downloadAnImage function. Notice the trailing closure block.

  1. downloanAnImage { (isSuccess: Bool) in
  2. if isSuccess {
  3. print("Done, bruh")
  4. }
  5. }
  6. // 1
  7. // 2
  8. // ...
  9. // 10000
  10. // "Done, bruh"

Source Code

3006_completion_handlers.playground

Resources

Completion Handlers in Swift with Bob

Conclusion

You’ve learned how to notify the user when the download has been completed. Some may feel uncomfortable with the syntax. I recommend you to read the article I’ve attached. When you enroll the UIKIt Fundamentals with Bob, you will learn how to pass data between classes, structs, and enums. You will use callbacks asynchronously with multi-threads to network with server.

Note: Learn Swift with Bob is available on Udemy. If you wish to receive a discount link, you may sign up here.