Bird
0
0

You have an array of integers and want to create a new array with only the even numbers using a for-in loop. Which code correctly does this?

hard📝 Application Q8 of 15
Swift - Loops
You have an array of integers and want to create a new array with only the even numbers using a for-in loop. Which code correctly does this?
Alet evens = [] for num in numbers { if num % 2 == 0 { evens.append(num) } }
Bvar evens = [Int]() for num in numbers { if num % 2 == 0 { evens.append(num) } }
Cvar evens = [Int] for num in numbers { if num % 2 == 0 { evens.append(num) } }
Dvar evens = Array for num in numbers { if num % 2 == 0 { evens.append(num) } }
Step-by-Step Solution
Solution:
  1. Step 1: Initialize an empty array correctly

    var evens = [Int]() for num in numbers { if num % 2 == 0 { evens.append(num) } } uses 'var evens = [Int]()' which correctly creates an empty integer array.
  2. Step 2: Use for-in loop with condition and append

    The loop checks if a number is even and appends it to evens array.
  3. Final Answer:

    var evens = [Int]()\nfor num in numbers {\n if num % 2 == 0 {\n evens.append(num)\n }\n} -> Option B
  4. Quick Check:

    Empty array init + append even numbers [OK]
Quick Trick: Initialize empty array with [Type]() before appending [OK]
Common Mistakes:
  • Using empty brackets [] without type
  • Missing parentheses in array initialization
  • Using Array without parentheses

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes