Need help with escaping closures.
I understand that the definition of escaping closures is If a closure is passed as an argument to a function and it is invoked after the function returns, the closure is escaping.
I believe there are a few scenarios where escaping closures are necessary.
Setting an outside variable as the passing closure
I understand this because the variable lives even after the function returns.
Asynchronous operations
Things like
Dispatch.main.async{}
orNetwork Request
.This is the part the I don't quite understand. I understand thatDispatch.main.async{}
runs on a different thread and that async operations take a while to complete hence the name async. However, I cannot understand how these operations outlive the scope of the function.
CodePudding user response:
When you call DispatchQueue.main.async{}
you are creating a closure (a block
in Objective-C) that is sent to the given dispatch queue. Your function will then continue running after the async
call and could end before the block has a chance to run on the DispatchQueue
. The closure has "escaped"!
The code in the block will actually be run when the block reaches the front of its DispatchQueue
The async
doesn't mean that the operation will take a long time, it means that this function (the one calling async
) will not pause to wait on the block to complete.
(if you DID want to pause and wait for the operation to complete, you could call sync
instead of async
).