Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3: Difference between DispatchQueue.main.async{} and DispatcQueue.main.async(execute:{})?

There's a very narrow semantic difference between the two, and I find myself wondering why both options exist. Are they in any way different functionally, or is one likely just an alias of the other?

like image 694
webbcode Avatar asked Apr 11 '17 21:04

webbcode


People also ask

What does DispatchQueue main Async do?

To summarize, DispatchQueue. async allows you to schedule work to be done using a closure without blocking anything that's ongoing. In most cases where you need to dispatch to a dispatch queue you'll want to use async .

What is DispatchQueue Global () async?

DispatchQueue. global() runs these kind of tasks in background threads. You can tell the queue about how important your task is, so that DispatchQueue can prioritize your task. You can do this by providing Quality-of-Service information.

Is main thread is sync or async?

sync means doing thing in main thread/UI thread and x. async means doing in background thread.

Is DispatchQueue main serial?

DispatchQueue. main (the main queue) is a serial queue. sync and async do not determine serialization or currency of a queue, but instead refer to how the task is handled. Synchronous function returns the control on the current queue only after task is finished.


1 Answers

There is no difference at all. They are, in fact, the very same method.

To the compiler,

myQueue.async(execute: { foo() })

is exactly the same as

myQueue.async {
  foo()
}

When the last argument of any function or method is a function, you can pass that argument as a trailing closure instead of passing it inside the argument list. This is done in order to make higher-order functions such as DispatchQueue.async feel more like part of the language, reduce syntactic overhead and ease the creation of domain-specific languages.

There's documentation on trailing closure syntax here.

And by the way, the idiomatic way to write my first example would be:

myQueue.async(execute: foo)
like image 184
Pedro Castilho Avatar answered Sep 28 '22 01:09

Pedro Castilho