0
0
Swiftprogramming~5 mins

Trailing closure syntax in Swift

Choose your learning style9 modes available
Introduction

Trailing closure syntax makes your code cleaner and easier to read when you pass a closure as the last argument to a function.

When you call a function that takes a closure as its last parameter.
When you want to write the closure outside the parentheses for better readability.
When you have a short block of code to run after a function completes.
When you want to make your Swift code look more like natural language.
Syntax
Swift
functionName(parameters) { closure code }

You can omit the parentheses if the closure is the only argument.

This syntax works only if the closure is the last argument in the function call.

Examples
Normal closure syntax: the closure is inside the parentheses.
Swift
func greet(name: String, action: () -> Void) {
    print("Hello, \(name)!")
    action()
}

greet(name: "Anna", action: {
    print("Welcome!")
})
Trailing closure syntax: the closure is written after the parentheses.
Swift
greet(name: "Anna") {
    print("Welcome!")
}
Trailing closure used with a standard library function for cleaner code.
Swift
let numbers = [1, 2, 3]
numbers.forEach { number in
    print(number * 2)
}
Sample Program

This program shows how trailing closure syntax works by passing a closure after the function call parentheses.

Swift
func performTask(completion: () -> Void) {
    print("Task started")
    completion()
    print("Task finished")
}

performTask {
    print("This is the trailing closure running.")
}
OutputSuccess
Important Notes

If the closure is the only argument, you can leave out the parentheses entirely.

Trailing closures improve readability especially when the closure code is long.

Summary

Trailing closure syntax lets you write the last closure argument outside the parentheses.

It makes your Swift code cleaner and easier to read.