0
0
Swiftprogramming~15 mins

For-in with where clause in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Filtering User Ages with For-in and Where Clause
📖 Scenario: You are managing a simple database of users and their ages. You want to find users who are adults (18 years or older) to send them a special offer.
🎯 Goal: Build a Swift program that uses a for-in loop with a where clause to filter and collect users who are 18 or older.
📋 What You'll Learn
Create a dictionary called users with these exact entries: "Alice": 17, "Bob": 20, "Charlie": 16, "Diana": 22
Create an empty array of strings called adultUsers to store names of adult users
Use a for-in loop with a where clause to iterate over users and select only those with age 18 or older
Inside the loop, append the user's name to adultUsers
💡 Why This Matters
🌍 Real World
Filtering data based on conditions is common in databases and apps, like selecting users eligible for offers.
💼 Career
Understanding loops with conditions helps in writing efficient queries and data processing code in many programming jobs.
Progress0 / 4 steps
1
Create the users dictionary
Create a dictionary called users with these exact entries: "Alice": 17, "Bob": 20, "Charlie": 16, "Diana": 22
Swift
Need a hint?

Use square brackets [] to create the dictionary and separate entries with commas.

2
Create the adultUsers array
Create an empty array of strings called adultUsers to store names of adult users
Swift
Need a hint?

Use var to create a mutable array and specify the type as [String].

3
Use for-in loop with where clause
Use a for-in loop with a where clause to iterate over users and select only those with age 18 or older. Use for (name, age) in users where age >= 18
Swift
Need a hint?

The where clause filters the loop to only run for users 18 or older.

4
Complete the filtering logic
Ensure the for-in loop with where clause appends the user's name to adultUsers inside the loop body
Swift
Need a hint?

Use the append method on adultUsers to add the name inside the loop.