0
0
Swiftprogramming~3 mins

Why Shorthand argument names ($0, $1) in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write less code and still do the same job perfectly?

The Scenario

Imagine you want to sort a list of names or filter numbers using a function. You write a full function with named arguments every time, even for simple tasks.

The Problem

This manual way is slow and clutters your code with extra words. It's easy to make mistakes by mixing up argument names or writing too much for simple actions.

The Solution

Shorthand argument names like $0 and $1 let you write quick, clean code without naming each argument. They make your code shorter and easier to read for simple closures.

Before vs After
Before
names.sorted(by: { name1, name2 in name1 < name2 })
After
names.sorted(by: { $0 < $1 })
What It Enables

You can write fast, clear code for small tasks without extra clutter, making your programs easier to understand and maintain.

Real Life Example

When you want to quickly sort a list of scores or filter a list of words, shorthand arguments let you do it in one neat line instead of many.

Key Takeaways

Manual argument naming can be long and confusing.

Shorthand names $0, $1 simplify closures.

They make code shorter, cleaner, and easier to read.