简体   繁体   中英

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?

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)

What you're referring to is called trailing closure syntax . It's a syntactic sugar for making closures easier to work with.

There are many other kinds of syntactic sugar features that pertain to closures, which I cover in my answer here .

As always, I highly recommend the Swift Language guide , which does a great job at explaining the basics like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM