Allows a nonescaping closure to temporarily be used as if it were allowed to escape.
- Xcode 8.3+
- Swift Standard Library
A nonescaping closure value that is made escapable for the duration of the execution of the
bodyhas a return value, that value is also used as the return value for the
Actually Escaping(_: do:)
A closure that is executed immediately with an escapable copy of
closureas its argument.
The return value, if any, of the
You can use this function to call an API that takes an escaping closure in a way that doesn’t allow the closure to escape in practice. The examples below demonstrate how to use
without in conjunction with two common APIs that use escaping closures: lazy collection views and asynchronous operations.
The following code declares an
all function that checks whether all the elements in an array match a predicate. The function won’t compile as written, because a lazy collection’s
filter(_:) method requires an escaping closure. The lazy collection isn’t persisted, so the
predicate closure won’t actually escape the body of the function; nevertheless, it can’t be used in this way.
without provides a temporarily escapable copy of
predicate that can be used in a call to the lazy view’s
filter(_:) method. The second version of
all compiles without error, with the compiler guaranteeing that the
escapable closure doesn’t last beyond the call to
Asynchronous calls are another type of API that typically escape their closure arguments. The following code declares a
perform(_: function that uses a dispatch queue to execute two closures concurrently.
perform(_: function ends with a call to the
sync(flags: method using the
.barrier flag, which forces the function to wait until both closures have completed running before returning. Even though the barrier guarantees that neither closure will escape the function, the
async(execute:) method still requires that the closures passed be marked as
@escaping, so the first version of the function does not compile. To resolve these errors, you can use
without to get copies of
g that can be passed to