Background: Trailing closure syntax is a syntactical construct in Swift introduced to enhance code readability when using closures at the end of function calls. It simplifies dealing with large and nested closures, especially in functional and declarative styles.
Problem: The standard declaration of closures with multiple parentheses complicates the visual structure of code, making it less understandable:
UIView.animate(withDuration: 0.3, animations: { ... })
As the size of the closure increases, this code becomes less readable.
Solution: Swift allows the last argument-function to be placed outside the parentheses:
UIView.animate(withDuration: 0.3) { // animation block }
If there are two or more closures, trailing closure syntax is only possible for the last closure parameter; the others must be specified within the parentheses.
Key features:
Can trailing closure syntax be applied if the closure is not the last parameter of the function?
No, only the last parameter can be specified as a trailing closure. If more than one closure is needed, only the last can be moved outside the parentheses; others must be provided inside the parentheses.
func fetch(url: String, completion: () -> Void, onError: () -> Void) fetch(url: "...", completion: { ... }) { // onError }
Can parentheses be omitted when calling a method with a single closure argument?
Yes, if a function accepts a single argument that is a closure, the parentheses can be omitted altogether:
func doWork(action: () -> Void) doWork { print("Task") }
Can trailing closure be used for functions with variadic parameters after the closure?
No, trailing closure syntax applies only if the closure is the last argument. There can be no variadic or other parameters after it. The following will raise an error:
func test(x: () -> Void, y: Int...) // ... call not possible with trailing closure
A call with two closure parameters formatted without trailing syntax takes up 5 screens vertically, making it harder to understand.
Pros:
Cons:
In the implementation of UICollectionViewCompositionalLayout, trailing closure is used — the layout block is easily readable, and the structure visually represents the hierarchy of layout components.
Pros:
Cons: