0
0
Swiftprogramming~30 mins

Where clauses for complex constraints in Swift - Mini Project: Build & Apply

Choose your learning style9 modes available
Where clauses for complex constraints
📖 Scenario: You are building a small app that manages a list of people with their ages and cities. You want to filter this list to find people who meet certain complex conditions.
🎯 Goal: Learn how to use where clauses in Swift loops to apply complex filtering conditions easily and clearly.
📋 What You'll Learn
Create an array of tuples representing people with name, age, and city
Create a variable for the minimum age to filter
Use a for loop with a where clause to find people who are at least the minimum age and living in a specific city
Print the names of the people who meet these conditions
💡 Why This Matters
🌍 Real World
Filtering lists of people or items based on multiple conditions is common in apps like contact managers, event planners, or shopping apps.
💼 Career
Understanding how to use <code>where</code> clauses helps write clean, readable code for filtering data efficiently in Swift development jobs.
Progress0 / 4 steps
1
Create the people data
Create an array called people with these exact tuples: ("Alice", 30, "New York"), ("Bob", 25, "Los Angeles"), ("Charlie", 35, "New York"), ("Diana", 22, "Chicago"), ("Eve", 28, "New York").
Swift
Need a hint?

Use square brackets to create an array of tuples. Each tuple has a name (String), age (Int), and city (String).

2
Set the minimum age filter
Create a constant called minAge and set it to 28.
Swift
Need a hint?

Use let to create a constant for the minimum age.

3
Filter people with a where clause
Write a for loop using for (name, age, city) in people where age >= minAge && city == "New York" to loop only over people who are at least minAge years old and live in "New York". Inside the loop, append the name to a new array called filteredNames. Create filteredNames as an empty array of strings before the loop.
Swift
Need a hint?

Use the where keyword after the for loop variables to filter the tuples. Append matching names to filteredNames.

4
Print the filtered names
Write a print statement to display the filteredNames array.
Swift
Need a hint?

Use print(filteredNames) to show the result.