0
0
Swiftprogramming~30 mins

Shorthand argument names ($0, $1) in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Shorthand Argument Names ($0, $1) in Swift
📖 Scenario: Imagine you are organizing a small party and you have a list of guests with their ages. You want to create a new list that shows only the guests who are adults (18 years or older).
🎯 Goal: You will learn how to use shorthand argument names $0 and $1 in Swift closures to filter and sort the guest list easily.
📋 What You'll Learn
Create a dictionary called guests with the exact entries: "Anna": 22, "Ben": 17, "Cara": 19, "David": 15, "Eva": 20
Create a variable called ageLimit and set it to 18
Use the filter method with a closure using shorthand argument name $0 to keep guests who are 18 or older
Use the sorted method with a closure using shorthand argument names $0 and $1 to sort guests by their names alphabetically
Print the filtered and sorted list of guests
💡 Why This Matters
🌍 Real World
Filtering and sorting data is common when managing lists like guest lists, contacts, or products.
💼 Career
Understanding shorthand argument names helps write concise and readable Swift code, useful for iOS app development.
Progress0 / 4 steps
1
Create the guest list dictionary
Create a dictionary called guests with these exact entries: "Anna": 22, "Ben": 17, "Cara": 19, "David": 15, "Eva": 20
Swift
Need a hint?

Use square brackets [] to create a dictionary with key-value pairs.

2
Set the age limit variable
Create a variable called ageLimit and set it to 18
Swift
Need a hint?

Use let to create a constant variable.

3
Filter guests who are adults using shorthand argument name
Use the filter method on guests with a closure using the shorthand argument name $0 to keep only guests whose age is greater than or equal to ageLimit. Store the result in a variable called adultGuests.
Swift
Need a hint?

Inside the closure, $0 represents each key-value pair (a tuple). Use $0.value to access the age.

4
Sort and print the adult guests
Use the sorted method on adultGuests with a closure using shorthand argument names $0 and $1 to sort guests by their names alphabetically. Then print the sorted list.
Swift
Need a hint?

Use $0.key and $1.key to compare guest names inside the closure.