swift
  1. swift-escaping-non-escaping-closures

Swift Escaping & Non-Escaping Closures

In Swift, closures are a powerful feature used for defining and manipulating functions in a concise way. They can be used as arguments to other functions, returned from functions, or stored as variables. There are two types of closures in Swift, namely, escaping and non-escaping closures.

Syntax

An escaping closure is defined as follows:

@escaping closureName: () -> Void

A non-escaping closure is defined as follows:

closureName: () -> Void

Example

Here is an example of a function that takes an escaping closure as an argument:

func fetchData(completionHandler: @escaping (String) -> Void) {
    DispatchQueue.global().async {
        // fetching data asynchronously
        completionHandler("data fetched successfully")
    }
}

Here is an example of a function that takes a non-escaping closure as an argument:

func printData(data: String, completionHandler: () -> Void) {
    print("Data: \(data)")
    completionHandler()
}

Output

In the first example, the closure passed to the fetchData function is executed after the data is fetched successfully. In the second example, the closure passed to the printData function is executed immediately after the data is printed.

Explanation

The difference between escaping and non-escaping closures lies in their lifespan. An escaping closure is a closure that is allowed to outlive the function it was passed to as an argument. This means that the closure can be stored as a property or variable and be executed at a later time after the function has returned, for example, in an asynchronous operation.

On the other hand, a non-escaping closure is executed within the lifespan of the function it was passed to as an argument. It cannot be stored as a property or variable, nor can it be executed at a later time.

Use

Escaping closures are most commonly used for asynchronous operations such as network requests or animations, where the closure needs to be executed at a later time. Non-escaping closures are used in situations where the closure needs to be executed immediately.

Important Points

  • Escaping closures are allowed to outlive the function they were passed to as an argument
  • Non-escaping closures are executed within the lifespan of the function they were passed to as an argument
  • Escaping closures are most commonly used for asynchronous operations
  • Non-escaping closures are used when the closure needs to be executed immediately

Summary

Escaping and non-escaping closures are an important feature of Swift programming language. Understanding the difference between these types of closures is essential for writing efficient and effective code. Escaping closures are a powerful tool for handling asynchronous operations, while non-escaping closures are useful for executing code immediately.

Published on: