Sobes.tech
Junior — Middle

Can you explain what the @escaping annotation means in Swift?

sobes.tech AI

Answer from AI

The @escaping annotation in Swift is used to indicate that a closure passed to a function may be called after the function has returned. This is important when the closure is stored and called asynchronously, such as in network request callbacks.

Without @escaping, a closure is considered non-escaping, meaning it must be called within the function body and cannot be stored for later invocation.

Example:

func fetchData(completion: @escaping () -> Void) {
    DispatchQueue.global().async {
        // Asynchronous work
        completion() // call the closure after exiting the function
    }
}

Here, completion is marked as @escaping because it is called asynchronously after fetchData exits.

Can you explain what the @escaping annotation means… - sobes.tech