I have the following code:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// Do stuff in the backgroud
dispatch_async(dispatch_get_main_queue()) {
// Do stuff on the UI thread
}
}
However it will not compile. The inner call to dispatch_async returns the following compile error:
Cannot invoke 'init' with an argument list of type '(dispatch_queue_t!, () -> () -> $T3)'
I can't seem to figure out how to write this so that it works like I used to be able to in Objective C. Thanks for any ideas!
A dispatch queue that is bound to the app's main thread and executes tasks serially on that thread. A dispatch queue that executes tasks concurrently using threads from the global thread pool. A dispatch queue that executes tasks serially in first-in, first-out (FIFO) order.
What is DispatchWorkItem? DispatchWorkItem is used to store a task on a dispatch queue for later use, and you can perform operations several operations on it, you can even cancel the task if it is not required later in the code.
Grand Central Dispatch (GCD) is a low-level API for managing concurrent operations. It can help you improve your app's responsiveness by deferring computationally expensive tasks to the background. It's an easier concurrency model to work with than locks and threads.
Grand Central Dispatch is a low-level C API that interacts directly with Unix level of the system. NSOperation is an Objective-C API and that brings some overhead with it. Instances of NSOperation need to be allocated before they can be used and deallocated when they are no longer needed.
Overview. Dispatch, also known as Grand Central Dispatch (GCD), contains language features, runtime libraries, and system enhancements that provide systemic, comprehensive improvements to the support for concurrent code execution on multicore hardware in macOS, iOS, watchOS, and tvOS.
Closures in Swift can have implicit returns if they only contain a single expression (see: Implicit Returns from Single-Expression Closures). Your inner closure most likely has a single expression in it to update the UI. The compiler is using the result of that expression as the return value for the closure which makes the closure's signature not match the signature dispatch_async
wants. Since dispatch_async
wants a closure that returns ()
(or Void
), the fix is to just add an explicit return
at the end of your closure:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// Do stuff in the backgroud
dispatch_async(dispatch_get_main_queue()) {
// Do stuff on the UI thread
return
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With