For-in with where clause in Swift - Time & Space Complexity
We want to understand how the time it takes to run a loop with a condition changes as the input grows.
How does adding a filter inside a loop affect the total work done?
Analyze the time complexity of the following code snippet.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers where number % 2 == 0 {
print(number)
}
This code loops through a list of numbers and prints only the even ones.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the array.
- How many times: Once for every item in the list, regardless of the condition.
As the list gets bigger, the loop checks each item once, even if it only prints some.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the size of the list.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items.
[X] Wrong: "Because we only print some items, the loop runs fewer times."
[OK] Correct: The loop still checks every item to decide if it should print, so it runs once per item.
Understanding how conditions inside loops affect performance helps you write efficient code and explain your reasoning clearly.
"What if we replaced the 'where' clause with an 'if' statement inside the loop? How would the time complexity change?"
Practice
where clause do in a for-in loop in Swift?Solution
Step 1: Understand the role of
Thewherein a loopwhereclause adds a condition to filter items during iteration.Step 2: Effect on loop execution
Only items that satisfy thewherecondition are processed in the loop.Final Answer:
It filters items so the loop runs only on those that meet the condition. -> Option CQuick Check:
wherefilters loop items [OK]
where filters items in the loop [OK]- Thinking
wherechanges variable type - Assuming it repeats the loop multiple times per item
- Believing it stops the loop early
where clause in a Swift for-in loop?Solution
Step 1: Recall correct
The correct syntax placesfor-in wheresyntaxwhereafter the sequence:for variable in sequence where condition.Step 2: Check each option
Onlyfor item in items where item.isActive { print(item) }matches the correct syntax. The other options have misplaced or incorrect keywords:wherebeforein,ifinstead ofwhere, or a semicolon beforewhere.Final Answer:
for item in items where item.isActive { print(item) } -> Option BQuick Check:
Correctwheresyntax [OK]
where right after in sequence [OK]- Placing
wherebeforein - Using
ifinstead ofwhere - Adding semicolon before
where
let numbers = [1, 2, 3, 4, 5], what will this code print?for num in numbers where num % 2 == 0 {
print(num)
}Solution
Step 1: Understand the loop and condition
The loop iterates over numbers and prints only those wherenum % 2 == 0, meaning even numbers.Step 2: Identify even numbers in the array
From [1, 2, 3, 4, 5], the even numbers are 2 and 4.Final Answer:
2 4 -> Option AQuick Check:
Print even numbers = 2 4 [OK]
- Printing odd numbers instead
- Printing all numbers ignoring
where - Expecting no output
let names = ["Anna", "Bob", "Cara"]
for name where name.hasPrefix("A") in names {
print(name)
}Solution
Step 1: Check the
Thefor-in wheresyntaxwhereclause must come afterin sequence, not before.Step 2: Identify the syntax error
The code placeswherebeforein names, which is invalid syntax.Final Answer:
Thewhereclause is placed beforeinincorrectly. -> Option AQuick Check:
wheremust followin[OK]
where after in [OK]- Placing
wherebeforein - Assuming
hasPrefixis invalid - Thinking loop variable must be var
let users = [ ["name": "Alice", "age": 25], ["name": "Bob", "age": 17], ["name": "Cara", "age": 30] ]
Using a
for-in loop with a where clause, how do you print only the names of users who are 18 or older?Solution
Step 1: Use correct
Thefor-in wheresyntaxwhereclause must come afterin usersto filter users by age.Step 2: Check type casting and condition
Use safe castas? Intwith default 0, then check if age >= 18.Step 3: Print the name safely
Accessuser["name"]!to print the name string.Final Answer:
for user in users where (user["age"] as? Int ?? 0) >= 18 { print(user["name"]!) } -> Option DQuick Check:
Correctfor-in wherewith safe cast [OK]
where after in users with safe cast [OK]- Placing
wherebeforein - Using
ifinstead ofwhere - Not casting age safely
- Forgetting to unwrap name
Ready to prove it?
Pass the test and this pattern moves unknown
