0
0
Swiftprogramming~5 mins

For-in loop with collections in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Afor number; numbers { print(number) }
Bfor number in numbers { print(number) }
Cfor (number in numbers) { print(number) }
Dloop number in numbers { print(number) }
What does the variable in a for-in loop represent when looping over a dictionary?
AThe index of each item
BOnly the keys
COnly the values
DEach key-value pair as a tuple
What will happen if you run a for-in loop on an empty array?
AThe loop body does not execute
BThe loop runs infinitely
CThe loop runs once with a nil value
DThe program crashes
Which collection types can you use with a for-in loop in Swift?
AArrays, dictionaries, sets, and ranges
BOnly arrays
COnly dictionaries
DOnly strings
Why might you choose a for-in loop over a while loop when working with collections?
AFor-in loops are more complex
BWhile loops are easier to read
CFor-in loops automatically handle iteration safely
DWhile loops are faster
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.