ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Swift Tutorial• 7 min read

Functions, Argument Labels & Trailing Closures

External vs internal parameter names, shorthand arguments $0, and @escaping

Functions in Swift have argument labels for readability at call sites. Closures are self-contained functional blocks of code that can be passed around and executed.

Argument Labels & Shorthand Closures

Argument labels: func greet(to person: String, from sender: String). At the call site, it reads like English: greet(to: "Bill", from: "Tim").

Shorthand Arguments: Inside inline closures, $0, $1 refer to closure arguments.

Trailing Closure Syntax: If the last argument of a function is a closure, it can be passed outside the function call parentheses.

Higher-Order Functions with Trailing Closures
let numbers = [5, 2, 8, 1, 9]

// Trailing closure syntax using shorthand $0 argument
let doubled = numbers.map { $0 * 2 }
let evens = numbers.filter { $0 % 2 == 0 }
let sorted = numbers.sorted { $0 < $1 }

print("Doubled:", doubled) // [10, 4, 16, 2, 18]
print("Sorted:", sorted)   // [1, 2, 5, 8, 9]
Trailing closures make functional data processing clean and concise.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What do the shorthand identifiers `$0` and `$1` represent inside a Swift closure?