📖 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
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
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
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
Hint
Use print(filteredNames) to show the result.
Practice
(1/5)
1. What is the main purpose of a where clause in Swift when used with generics?
easy
A. To define a function's return type
B. To declare a new generic type
C. To add extra conditions that generic types must satisfy
D. To create a loop over a collection
Solution
Step 1: Understand generics and constraints
Generics allow flexible types, but sometimes we want to restrict them to certain types or protocols.
Step 2: Role of where clause
The where clause adds extra conditions to generic parameters, ensuring they meet specific requirements.
Final Answer:
To add extra conditions that generic types must satisfy -> Option C
Quick Check:
Where clause = extra generic constraints [OK]
Hint: Where clauses add conditions to generics or loops [OK]
Common Mistakes:
Confusing where clause with function return type
Thinking where declares new types
Using where to create loops
2. Which of the following is the correct syntax for using a where clause in a generic function in Swift?
easy
A. func example<T>(value: T) where T: Equatable {}
B. func example(value: T) {}
C. func example<T>(value: T) if T: Equatable {}
D. func example<T>(value: T) where T == Equatable {}
Solution
Step 1: Recall correct where clause syntax
In Swift, the where clause comes after the generic parameter list and before the function body.
Step 2: Check each option
func example<T>(value: T) where T: Equatable {} uses correct syntax: func example<T>(value: T) where T: Equatable {}. Others misuse placement or keywords.
Final Answer:
func example<T>(value: T) where T: Equatable {} -> Option A
Quick Check:
Where clause after generics = correct syntax [OK]
Hint: Where clause always follows generic parameters () [OK]
Common Mistakes:
Placing where inside angle brackets
Using if instead of where
Using == instead of : for protocol conformance
3. What will be the output of the following Swift code?
func printIfEqual(_ a: T, _ b: U) where T == U, T: Equatable {
if a == b {
print("Equal")
} else {
print("Not Equal")
}
}
printIfEqual(5, 5)
printIfEqual("hi", "hello")
medium
A. Equal\nEqual
B. Compilation error
C. Not Equal\nNot Equal
D. Equal\nNot Equal
Solution
Step 1: Understand the where clause constraints
The function requires T and U to be the same type and conform to Equatable, so both arguments must be comparable and same type.
Step 2: Analyze the calls
First call: 5 and 5 are Ints, equal, so prints "Equal". Second call: "hi" and "hello" are Strings, same type, but not equal, so prints "Not Equal".
Final Answer:
Equal
Not Equal -> Option D
Quick Check:
Same type & Equatable check = output [OK]
Hint: Check type equality and Equatable conformance for output [OK]
Common Mistakes:
Assuming different types allowed
Expecting compilation error
Ignoring Equatable conformance
4. Identify the error in this Swift function using a where clause:
func compareValues(a: T, b: U) where T: Comparable, U: Comparable {
if a < b {
print("a is less")
} else {
print("b is less or equal")
}
}
medium
A. Missing return type in function signature
B. Cannot compare different generic types with < operator
C. where clause syntax is incorrect
D. Function parameters should be optional
Solution
Step 1: Understand the where clause constraints
The function requires T and U to be Comparable, but they can be different types.
Step 2: Check the comparison operation
Comparing a < b is invalid because Swift cannot compare two different types even if both are Comparable.
Final Answer:
Cannot compare different generic types with < operator -> Option B
Quick Check:
Different Comparable types can't be compared directly [OK]
Hint: Comparable types must be same to compare with < [OK]
Common Mistakes:
Assuming Comparable allows cross-type comparison
Ignoring type mismatch in operators
Thinking where clause syntax is wrong
5. Given a generic function that filters an array of elements only if they conform to both Comparable and Numeric, which where clause correctly expresses this constraint?
To require a type to conform to multiple protocols, use the & symbol between them.
Step 2: Analyze each option
T: Comparable & Numeric correctly uses T: Comparable & Numeric. T: Comparable, Numeric uses comma which is invalid syntax. T: Comparable where T: Numeric misuses where inside where clause. T: Numeric or Comparable uses 'or' which is not valid.
Final Answer:
T: Comparable & Numeric -> Option A
Quick Check:
Use & to combine protocols in where clause [OK]
Hint: Use & to combine multiple protocol constraints [OK]
Common Mistakes:
Using commas instead of &
Misplacing where keyword
Using 'or' instead of &
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.