0
0
Swiftprogramming~5 mins

Array iteration and enumerated in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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: Blue
Click to reveal answer
What does the enumerated() method return when called on an array?
AOnly the elements of the array
BA sequence of (index, element) pairs
COnly the indices of the array
DA reversed array
How do you access the index and value inside a for-in loop using enumerated()?
Afor (index, value) in array.enumerated()
Bfor index in array.enumerated()
Cfor value in array.enumerated()
Dfor array in (index, value)
Which of these is a correct way to iterate over an array numbers to print each element?
Afor number in numbers { print(number) }
Bnumbers.forEach(print)
CAll of the above
Dfor (index, number) in numbers.enumerated() { print(number) }
What type is the index provided by enumerated()?
AInt
BString
CDouble
DBool
If you want to print the position starting from 1 instead of 0 using enumerated(), what should you do?
ASubtract 1 from the index
BUse <code>enumerated(startingAt: 1)</code>
CYou cannot change the starting index
DAdd 1 to the index inside the loop
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.