0
0
Swiftprogramming~5 mins

Shorthand argument names ($0, $1) in Swift

Choose your learning style9 modes available
Introduction

Shorthand argument names let you write shorter, simpler code when using closures. They save time by avoiding naming each argument.

When you want to quickly sort a list without writing a full closure.
When you need to transform items in a list with a simple operation.
When filtering a list based on a quick condition.
When you want to keep your code clean and easy to read for small closures.
Syntax
Swift
list.method { $0, $1 in
    // use $0 for first argument
    // use $1 for second argument
}

$0 is the first argument, $1 is the second, and so on.

You don't have to write the argument names or types explicitly.

Examples
Sorts numbers using $0 and $1 as the two items to compare.
Swift
let numbers = [3, 1, 2]
let sorted = numbers.sorted { $0 < $1 }
Transforms each name to uppercase using $0 as the current item.
Swift
let names = ["Anna", "Bob", "Cindy"]
let uppercased = names.map { $0.uppercased() }
Filters scores to keep only those 60 or above using $0 as the score.
Swift
let scores = [85, 42, 90, 75]
let passed = scores.filter { $0 >= 60 }
Sample Program

This program shows sorting, mapping, and filtering using shorthand argument names $0 and $1.

Swift
let fruits = ["apple", "banana", "cherry"]

// Sort fruits alphabetically
let sortedFruits = fruits.sorted { $0 < $1 }
print("Sorted fruits:", sortedFruits)

// Make all fruits uppercase
let upperFruits = fruits.map { $0.uppercased() }
print("Uppercase fruits:", upperFruits)

// Filter fruits that start with 'b'
let bFruits = fruits.filter { $0.hasPrefix("b") }
print("Fruits starting with 'b':", bFruits)
OutputSuccess
Important Notes

Shorthand arguments only work inside closures.

Use them for short closures to keep code clean.

For complex closures, naming arguments can improve clarity.

Summary

Shorthand argument names like $0 and $1 let you write shorter closures.

$0 is the first argument, $1 the second, and so on.

They make simple tasks like sorting, mapping, and filtering easier and cleaner.