Trailing Closures

Introduction

Welcome to Lesson 5 of Intro to Functional Swift. You will learn how to beautify a closure block.

Problem

A closure is too long to pass through a function

Design Function

Create a function which takes two parameters: Int and () -> Void

  1. func trailingClosure(number: Int, closure: () -> Void) {
  2. print("You've entered \(number)")
  3. closure()
  4. }

Design Closure Block

Create a closure block which will be passed to trailingClosure

  1. func helloFunc() -> Void {
  2. print("Hello, Function!")
  3. }
  4. helloFunc // () -> Void
  5. let helloClosure = {
  6. print("Hello, Closure!")
  7. }

Execute Function

Pass helloFunc and helloClosure to the function.

  1. trailingClosure(number: 100, closure: helloFunc)
  2. trailingClosure(number: 100, closure: helloClosure)

If a function’s last parameter requires a closure block, you may beautify.

  1. // Trailing Closure #1
  2. trailingClosure(number: 100, closure: { print("Hello!!!") })
  3. // Trailing Closure #2
  4. trailingClosure(number: 100) { print("Hello!!!!!") }

Another Example

  1. func trailingClosures(number: Int, closure: (Int) -> Int) {
  2. let newNumber = closure(number)
  3. print(newNumber)
  4. }

The last parameter of the function above requires (Int) -> Int. You may use a trailing closure block instead.

  1. // Without trailing closure
  2. trailingClosures(number: 1000, closure: { number in number * number })
  3. // With trailing clousre
  4. trailingClosures(number: 500) { number in number * number }
  5. trailingClosures(number: 400) { $0 * $0 }

Source Code

3005_trailing_closures.playground

Conclusion

You’ve learned how to beautify a function whose last parameter contains a closure block. Trailing closures improve readability and zenness. You will see its beauty throughout the course.

In the following lesson, you will learn one of the most dreaded topics of all time: Completion handlers. You will learn how to design on your own. It’s time to level up.

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