Bird
0
0

How can you use enumerated() to find the first element in an array nums that is greater than 10 and print its index?

hard📝 Application Q9 of 15
Swift - Collections
How can you use enumerated() to find the first element in an array nums that is greater than 10 and print its index?
Anums.firstIndex(where: { $0 > 10 })
Bfor num in nums { if num > 10 { print(num) break } }
Cfor (index, num) in nums.enumerated() { if num > 10 { print(index) break } }
Dnums.enumerated().filter { $0.element > 10 }.first?.offset
Step-by-Step Solution
Solution:
  1. Step 1: Understand enumerated() usage for index and element

    Using enumerated() allows access to both index and element in the loop.
  2. Step 2: Check which option finds first element > 10 and prints index

    for (index, num) in nums.enumerated() { if num > 10 { print(index) break } } loops with enumerated(), checks condition, prints index, and breaks to stop at first match. for num in nums { if num > 10 { print(num) break } } prints element, not index. nums.enumerated().filter { $0.element > 10 }.first?.offset returns optional index but does not print. nums.firstIndex(where: { $0 > 10 }) uses a different method.
  3. Final Answer:

    for (index, num) in nums.enumerated() { if num > 10 { print(index) break } } -> Option C
  4. Quick Check:

    Loop with enumerated() and break on first match [OK]
Quick Trick: Use break after first match in enumerated() loop [OK]
Common Mistakes:
  • Printing element instead of index
  • Not breaking loop after first match
  • Using wrong method for index

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes