Recall & Review
beginner
What does the
enumerated() method do when used on an array in Swift?The
enumerated() method returns a sequence of pairs, where each pair contains an index and the corresponding element from the array. This helps to access both the position and value during iteration.Click to reveal answer
beginner
How do you write a simple
for-in loop to iterate over all elements in a Swift array named fruits?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
Why might you want to use
enumerated() instead of a simple for-in loop?Using
enumerated() lets you know the index of each element while looping. This is useful when you need to know the position of the item, like numbering a list or updating elements by index.Click to reveal answer
intermediate
What is the type of the value returned by
enumerated() on an array?It returns a sequence of tuples where each tuple has two parts: an
Int index and the element of the array's type. For example, (Int, String) if the array holds strings.Click to reveal answer
beginner
Write a Swift code snippet that prints the index and value of each element in an array
colors using enumerated().let colors = ["Red", "Green", "Blue"]
for (index, color) in colors.enumerated() {
print("\(index): \(color)")
}
This prints:<br>0: Red<br>1: Green<br>2: BlueClick to reveal answer
What does the
enumerated() method return when called on an array?✗ Incorrect
enumerated() returns pairs of index and element, allowing access to both during iteration.How do you access the index and value inside a
for-in loop using enumerated()?✗ Incorrect
You use tuple unpacking:
for (index, value) in array.enumerated().Which of these is a correct way to iterate over an array
numbers to print each element?✗ Incorrect
All listed methods correctly iterate and print elements of the array.
What type is the index provided by
enumerated()?✗ Incorrect
The index is always an
Int representing the position in the array.If you want to print the position starting from 1 instead of 0 using
enumerated(), what should you do?✗ Incorrect
You add 1 to the index manually inside the loop to start counting from 1.
Explain how to use
enumerated() to loop through an array and access both the index and the element.Think about how you get both position and value in one loop.
You got /3 concepts.
Describe the difference between a simple
for-in loop over an array and using enumerated() in Swift.One gives you just the items, the other gives you items with their positions.
You got /3 concepts.