6

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?

webbcode
  • 336
  • 3
  • 9

2 Answers2

13

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)
Pedro Castilho
  • 10,174
  • 2
  • 28
  • 39
3

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.

Community
  • 1
  • 1
Alexander
  • 59,041
  • 12
  • 98
  • 151