Bird
0
0

Which Swift code snippet correctly iterates over an array values using enumerated() to access both index and element?

easy📝 Conceptual Q2 of 15
Swift - Collections
Which Swift code snippet correctly iterates over an array values using enumerated() to access both index and element?
Afor idx, val in values.enumerated { print(idx, val) }
Bfor (idx, val) in values.enumerated() { print(idx, val) }
Cfor idx in values.enumerated() { print(idx) }
Dfor val in values.enumerated() { print(val) }
Step-by-Step Solution
Solution:
  1. Step 1: Check syntax of enumerated()

    The method enumerated() must be called with parentheses.
  2. Step 2: Check tuple unpacking

    for (idx, val) in values.enumerated() { print(idx, val) } correctly uses tuple unpacking with parentheses: (idx, val).
  3. Step 3: Analyze other options

    for idx, val in values.enumerated { print(idx, val) } misses parentheses after enumerated. Options C and D do not unpack the tuple correctly.
  4. Final Answer:

    A -> Option B
  5. Quick Check:

    Use parentheses with enumerated() and tuple unpacking [OK]
Quick Trick: Use for (index, element) in array.enumerated() [OK]
Common Mistakes:
  • Omitting parentheses after enumerated
  • Not unpacking tuple with parentheses

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes