Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Escaping Closures
Written by Team Kodeco

Swift closures can be classified into two types: escaping and non-escaping. Escaping closures are those that outlive the function they are defined in, while non-escaping closures are those that are used within the function and are deallocated when the function returns.

An escaping closure is denoted by the keyword “escaping” before the parameter type in the function definition.

import Foundation

func doSomething(completion: @escaping () -> Void) {
  DispatchQueue.main.async {
    completion()
  }
}

In this example, the completion closure is marked as escaping, which means it’ll be called after the doSomething function has returned.

When working with escaping closures it’s important to consider the lifetime of the closure and the objects it captures, as it can lead to retain cycles if you aren’t careful.

© 2024 Kodeco Inc.