In Swift, how can a closure expression passed to a function be shortened, and how do trailing and multiple trailing closures change the call site?
answer
- context supplies the types
- single expression returns itself
- $0, $1 by position
- outside the parentheses
- first unlabeled, the rest labeled
basics
~20 sSwift infers a closure's parameter and return types from the call, so a single-expression closure can drop its types, return and parameter names ($0, $1). A final closure argument can move after the parentheses as a trailing closure.
solid answer
~50 sThe full form is `{ (lhs: Download, rhs: Download) -> Bool in return lhs.bytes > rhs.bytes }`. Because `sorted(by:)` already declares the function type it expects, Swift infers the parameter and return types, a single-expression body returns its value implicitly, and the names can become `$0` and `$1`, leaving `{ $0.bytes > $1.bytes }`. When the closure is the last argument it can be written after the parentheses as a trailing closure, and the parentheses disappear when it is the only argument: `finished.sorted { $0.bytes > $1.bytes }`. Since Swift 5.3 a call can take several trailing closures: the first is unlabeled and every later one carries its argument label, as in `download(url) { fraction in … } completion: { result in … }`. Shorthand names suit one-line bodies; a multi-line closure reads better with named parameters.
code
swift · 31 linesstruct Download {
let url: String
let bytes: Int
}
func download(
_ url: String,
progress: ((Double) -> Void)? = nil,
completion: @escaping (Download) -> Void
) {
progress?(1.0)
completion(Download(url: url, bytes: url.count * 1_000))
}
let finished = [Download(url: "a.png", bytes: 300), Download(url: "bb.png", bytes: 900)]
// The same comparison, shortened step by step.
let a = finished.sorted(by: { (lhs: Download, rhs: Download) -> Bool in return lhs.bytes > rhs.bytes })
let b = finished.sorted(by: { lhs, rhs in lhs.bytes > rhs.bytes })
let c = finished.sorted { $0.bytes > $1.bytes }
print(a[0].url, b[0].url, c[0].url)
// One trailing closure: the defaulted progress parameter is skipped, so it becomes completion.
download("cat.png") { result in print("saved", result.bytes) }
// Multiple trailing closures: the first is unlabeled, every later one carries its label.
download("dog.png") { fraction in
print("progress", fraction)
} completion: { result in
print("saved", result.bytes)
}go deeper
Recall the four shortenings in order: inferred types, implicit return, $0-style names, trailing syntax. Be able to rewrite a full closure into its shortest form and back.
Explain that every shortening rests on the parameter's declared function type, and show the multiple-trailing-closure call shape with the first closure unlabeled and the rest labeled.
Know how the forward scan picks the parameter for an unlabeled trailing closure, why defaulted closure parameters can bind differently in Swift 5 and Swift 6 modes, and how labeling fixes it.
Treat trailing-closure friendliness as API design: order closure parameters so the forward scan lands on the obvious one, and set a team convention for when shorthand names stop being readable.
## The full closure expression A **closure expression** is an unnamed function written inline: `{ (parameters) -> ReturnType in statements }`. The keyword `in` separates the signature from the body. Writing everything out is always legal, but Swift lets you remove most of it whenever the surrounding call already says what the closure must look like. Take a list of finished image downloads sorted by size, largest first. `sorted(by:)` expects a function of type `(Element, Element) -> Bool`, so the compiler knows the parameter and return types before it reads your closure. ## Shortening a closure step by step 1. **Full form:** `finished.sorted(by: { (lhs: Download, rhs: Download) -> Bool in return lhs.bytes > rhs.bytes })`. 2. **Inferred types:** the context fixes both parameter types and the `Bool` result, so `{ lhs, rhs in return lhs.bytes > rhs.bytes }` is equivalent. 3. **Implicit return:** a closure whose body is a **single expression** returns that expression's value, so `return` can go: `{ lhs, rhs in lhs.bytes > rhs.bytes }`. 4. **Shorthand argument names:** parameters are also available positionally as `$0`, `$1`, `$2`, … When you use them and drop the names and types, you also drop `in`: `{ $0.bytes > $1.bytes }`. Some details matter in review: - Closure parameters are **constants**; to change one, copy it into a local `var` inside the body. - Implicit return applies to a single-expression body only. A body with two statements needs an explicit `return`; otherwise the compiler reports `missing return in closure expected to return 'Int'` (for an `Int` result). - If the omitted types cannot be inferred, compilation fails: every shortening relies on the context's function type. - A closure that has a **capture list** still needs `in`, even when it uses `$0`. Passing an operator such as `>` directly as the comparison is a separate topic — functions and operators as values, covered with first-class callables. ## Trailing closures When a closure is the **final argument**, you may write it after the call's closing parenthesis. This is a **trailing closure**: still an argument, just written outside. - The first trailing closure is written **without its argument label**. - If the closure is the only argument, the empty parentheses can be dropped too: `finished.sorted { $0.bytes > $1.bytes }`. - Trailing syntax pays off when the body spans several lines, as completion handlers usually do. ## Multiple trailing closures and the forward scan Since **Swift 5.3** (SE-0279) a call can end with several trailing closures. The first stays unlabeled; each later one is written with its argument label: ```swift download("dog.png") { fraction in print("progress", fraction) } completion: { result in print("saved", result.bytes) } ``` Which parameter receives the **unlabeled** closure is decided by the **forward scan** (SE-0286): the compiler walks the parameters left to right and gives it to the next parameter whose type is a function type, or a function type wrapped in `Optional`. A heuristic skips a parameter that has a default value when a later parameter still needs an argument. That is why `download("cat.png") { result in … }` binds to `completion` even though the defaulted `progress` parameter comes first. | Call | Swift 5 language mode | Swift 6 language mode | |---|---|---| | `download("a") { … }` with defaulted `progress`, required `completion` | binds `completion` | binds `completion` | | `notify { … }` where `onSuccess` and `onFailure` are both defaulted closures | binds `onFailure` (old backward match) with a warning | binds `onSuccess` | In Swift 5 mode the compiler still falls back to the older backward match when it and the forward scan disagree, and warns: `backward matching of the unlabeled trailing closure is deprecated; label the argument with 'onFailure' to suppress this warning`. Swift 6 mode matches forward only. Labeling the argument removes the ambiguity in both. ## A Swift 6.4 addition Swift 6.4 (SE-0508) lets a trailing closure follow an array type in an expression, so `[String] { … }` calls an `Array` initializer that takes a closure. Earlier releases did not treat that closure as part of the expression, so such code failed to compile. ## Readability guidelines - Use `$0` in one-line closures where the meaning is obvious; name parameters once the body grows. - Prefer trailing syntax for the last, longest closure; label every closure when an API takes several defaulted ones.
- In Swift, why does `download("cat.png") { result in … }` bind to `completion` when a defaulted `progress` closure parameter comes first?The forward scan would offer the unlabeled trailing closure to `progress` first, but a heuristic skips a parameter that has a default value when a later parameter, here `completion`, still requires an argument. So `progress` keeps its `nil` default and the closure becomes `completion`, in both Swift 5 and Swift 6 language modes.
- In Swift, why can the same trailing-closure call bind to different parameters in Swift 5 and Swift 6 language modes?When two defaulted closure parameters could both take the unlabeled closure, Swift 5 mode keeps the pre-5.3 backward match, scanning from the last parameter, and warns that backward matching is deprecated. Swift 6 mode uses only the forward scan, so the first parameter wins. Writing the label, such as `onFailure:`, makes the call mean the same in both modes.
- In Swift, when does a closure that uses `$0` still have to write `in`?When it has a capture list. `{ [weak self] in self?.apply($0) }` must keep `in` to end the capture list, even though the parameters are named positionally. Without a capture list, using `$0` and dropping names and types means dropping `in` as well.
- A trailing closure is a different kind of value from a closure in parentheses.
- Every trailing closure after the first is also written without its label.
- A single-expression closure still needs an explicit return keyword.
- An unlabeled trailing closure always binds to the function's last parameter.
- Shorthand $0 and $1 names make long multi-line closures easier to review.
Assumes Swift 6.4: multiple trailing closures date from Swift 5.3, Swift 5 mode still falls back to backward matching with a warning while Swift 6 mode matches forward only, and trailing closures after an array type arrived in 6.4.