Escaping and Autoclosures

Introduction

Welcome to the last lesson of Swift Memory Management. You will learn at which circumstances you use escaping and autoclosures. No fear closures.

Problem

What are those?

Escaping Closures

Definition: If the closure block is executed after the function returns, you must add @escaping.

Scenario 1

Create an array whose type is [() -> Void].

  1. var closureBlocks: [() -> Void] = []

Create function whose parameter type is () -> Void. The function will take the parameter and append to the closureBlocks array.

  1. func funcWithClosure(closure: @escaping () -> Void) {
  2. closureBlocks.append(closure)
  3. }

The @escaping keyword is added since the closure can be called after the function returns/executes.

Scenario 2

Asynchronous operation does not execute code line-by-line. Instead, it runs many at the same time.

  1. import Foundation
  2. func funcWithNetworkingClosure(closure: @escaping () -> Void) {
  3. DispatchQueue.global().async {
  4. closure() // Ex) downloading
  5. }
  6. }

The @escaping is added automatically.

When you pass a closure block to the function, the closure block is executed even after the function returns.

  1. funcWithNetworkingClosure {
  2. for _ in 1...1000 {
  3. print("downloading")
  4. }
  5. }
  6. // "downloading"
  7. // "downloading"
  8. // ...
  9. // execute other operations
  10. // "downloading"
  11. // "downloading"
  12. // execute other operations

Note: If you wish to learn more about multi-tasking and asynchronous operations,, you may read Intro to Grand Central Dispatch in Swift 3 with Bob

Normal Function

A normal function is @nonescaping by default. In other words, the closure is executed before the function returns/finishes.

  1. class Normal {
  2. let name = "Bob"
  3. func normalFunctionWithClosure(closure: (String) -> Void) {
  4. closure(self.name)
  5. }
  6. }
  7. Normal().normalFunctionWithClosure { (myName) in
  8. print(myName)
  9. }

When you execute the function, the closure block is initialized and deallocated as the function returns. The function also gets deallocated. It happens almost simultaneously. If the function is @escaping, however, the closure block is not deallocated while the function block is.

Benefits of Non-Escaping

  1. There is no retain cycle for non-escaping functions since everything is deallocated
  2. You may use self keyword without worrying about memory leak
  3. Performance and the ability for the compiler to optimize

Introducing @autoclosures

  1. func checkIDCard(hasCard: () -> Bool) {
  2. if hasCard() {
  3. print("You've an ID")
  4. }
  5. }
  6. checkIDCard(hasCard: { return true})
  7. checkIDCard(hasCard: { true })
  8. checkIDCard { true }

The @autoclosure keyword allows you to pass a closure block with no brackets.

  1. func checkIDCard(hasCard: @autoclosure () -> Bool) {
  2. if hasCard() {
  3. print("You've an ID")
  4. }
  5. }
  6. checkIDCard(hasCard: true)

Lazy Init Capture

You’ve learned how to initialize an object with lazy and closures. However, you must be careful of potential retain cycle. Let us find out if there is one.

Create Lazy

  1. class BobGreet {
  2. var name = "Bob the Developer"
  3. lazy var greeting: String = {
  4. return "Hello, \(self.name)"
  5. }()
  6. deinit {
  7. print("I'm gone, bruh ?‍")}
  8. }

The closure block as a strong reference to self. However, let us attempt to deallocate regardless.

Deallocate

  1. var bobGreet: BobGreet? = BobGreet()
  2. bobGreet?.greeting
  3. bobGreet = nil // "I'm gone, bruh ?‍"

Important: a closure block with a lazy property is @noescape by default.

Source Code

5004_escaping_autoclosures.playground

Resources

Intro to Grand Central Dispatch in Swift 3 with Bob

Conclusion

You’ve learned 3 concepts. First, a function requires the @escaping keyword if the closure block in the parameter is executed after the function returns. Second, the @auotoclosure keyword is used to enter a closure block without brackets. However, the closure must have no parameters. Lastly, there is no retain cycle in lazy properties.

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