The 1st closure passed to this function is put on an queue in an asynch manner, then the function will immediately place the 2nd closure on the main queue asynchronously. The 2nd closure requires the “result” constant as an input parameter, what coordination takes place under the covers to make sure the result is passed from one asynchronous task to the other asynchronous task?
then the function will immediately place the 2nd closure on the main queue asynchronously
Not so. The call to DispatchQueue.main.async is part of the code block that has been passed in to the call to queue.async {}. So the queue will execute that block, first doing let result = backgroundWork(), then doing DispatchQueue.main.async { mainWork(result) }. Some indenting and comments will help you see it:
func execute(backgroundWork: @escaping () -> Result,
mainWork: @escaping (Result) -> ()) {
queue.async {
// start of block in queue
let result = backgroundWork()
DispatchQueue.main.async {
mainWork(result)
}
// end of block in queue
}
}