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?
2 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)

- 10,174
- 2
- 28
- 39
-
In this case, you may as well do: `myQueue.async(execute: foo)` :) – Alexander Apr 11 '17 at 22:08
-
I tried to make the parallel more obvious, but yeah, that would be the more idiomatic way :) – Pedro Castilho Apr 11 '17 at 22:28
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.