Sobes.tech
Junior — Middle

When is a closure in Swift considered escaping, even if the @escaping keyword is not specified in the code?

sobes.tech AI

Answer from AI

In Swift, a closure is considered escaping if it is stored and called after the function it was passed to has finished. Usually, such closures need to be explicitly marked with @escaping.

However, there are cases where a closure is considered escaping even without an explicit @escaping:

  • If the closure is used as a parameter of a function that is itself declared with @escaping for that parameter.
  • When using closures in asynchronous operations, for example, in APIs where the closure is stored for later invocation (such as in DispatchQueue or URLSession).

That is, if a closure is passed further and called after exiting the current function, the compiler requires @escaping. If @escaping is not specified, but the closure is actually stored and called later, it will result in a compilation error.

Example:

func performAsyncTask(completion: @escaping () -> Void) {
    DispatchQueue.global().async {
        // Asynchronous work
        completion() // called later
    }
}

If you remove @escaping, the compiler will produce an error because completion is called after exiting the function.

Thus, a closure is considered escaping when it is stored and called later, even if @escaping is not explicitly specified in the code (for example, when inheriting the signature or using APIs where it is implied).

When is a closure in Swift considered escaping, even… - sobes.tech