Recall & Review
beginner
What is a
for-in loop used for in Swift?A
for-in loop is used to repeat a block of code for each item in a collection, like an array or dictionary.Click to reveal answer
beginner
How do you loop through all elements in an array named
fruits using a for-in loop?You write: <br>
for fruit in fruits {<br> print(fruit)<br>}<br>This prints each fruit in the array one by one.Click to reveal answer
intermediate
Can you use a
for-in loop to iterate over a dictionary in Swift? How?Yes! You loop over key-value pairs like this:<br>
for (key, value) in dictionary {<br> print("\(key): \(value)")<br>}Click to reveal answer
beginner
What happens if you use a
for-in loop on an empty collection?The loop body does not run at all because there are no items to go through.
Click to reveal answer
intermediate
Why is a
for-in loop preferred over a traditional while loop for collections?Because it is simpler, safer, and less error-prone. It automatically goes through each item without needing to manage indexes.
Click to reveal answer
Which of the following is the correct way to loop through an array
numbers in Swift?✗ Incorrect
Option B uses the correct Swift syntax for a for-in loop.
What does the variable in a for-in loop represent when looping over a dictionary?
✗ Incorrect
In Swift, looping over a dictionary gives you each key-value pair as a tuple.
What will happen if you run a for-in loop on an empty array?
✗ Incorrect
The loop body does not run because there are no items to iterate over.
Which collection types can you use with a for-in loop in Swift?
✗ Incorrect
Swift's for-in loop works with any collection type like arrays, dictionaries, sets, and ranges.
Why might you choose a for-in loop over a while loop when working with collections?
✗ Incorrect
For-in loops automatically handle going through each item safely without manual index management.
Explain how a for-in loop works with an array in Swift. Include an example.
Think about how you say 'for each item in the list, do something'.
You got /3 concepts.
Describe how to use a for-in loop to iterate over a dictionary and access both keys and values.
Remember dictionaries store pairs, so you get two things each time.
You got /3 concepts.