Bird
Raised Fist0
Swiftprogramming~10 mins

Map, filter, reduce patterns in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Map, filter, reduce patterns
Start with Array
↓
Apply Map
→Transform each element
↓
Apply Filter
→Keep elements matching condition
↓
Apply Reduce
→Combine elements into one value
↓
Result
This flow shows how an array is transformed step-by-step by map, filter, and reduce functions.
Execution Sample
Swift
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map { $0 * 2 }
let even = doubled.filter { $0 % 2 == 0 }
let sum = even.reduce(0) { $0 + $1 }
This code doubles numbers, keeps even ones, then sums them.
Execution Table
StepOperationInputOutputExplanation
1Map[1, 2, 3, 4, 5][2, 4, 6, 8, 10]Each number multiplied by 2
2Filter[2, 4, 6, 8, 10][2, 4, 6, 8, 10]All are even, so all kept
3Reduce[2, 4, 6, 8, 10]30Sum of all elements
4End--No more operations
💡 All steps completed; final result is 30
Variable Tracker
VariableStartAfter MapAfter FilterAfter Reduce
numbers[1, 2, 3, 4, 5][1, 2, 3, 4, 5][1, 2, 3, 4, 5][1, 2, 3, 4, 5]
doubled-[2, 4, 6, 8, 10][2, 4, 6, 8, 10][2, 4, 6, 8, 10]
even--[2, 4, 6, 8, 10][2, 4, 6, 8, 10]
sum---30
Key Moments - 3 Insights
Why does filter keep all elements after map in this example?
Because after map, all numbers are even (2,4,6,8,10), so the filter condition ($0 % 2 == 0) is true for all, as shown in execution_table row 2.
What does reduce(0) { $0 + $1 } mean?
It means start with 0, then add each element one by one to get the total sum, as shown in execution_table row 3.
Does map change the original array?
No, map creates a new array with transformed elements; the original 'numbers' stays the same, as seen in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 1, what is the output of map?
A[2, 4, 6, 8, 10]
B[1, 2, 3, 4, 5]
C[1, 4, 9, 16, 25]
D[0, 2, 4, 6, 8]
💡 Hint
Check the 'Output' column in execution_table row 1.
At which step does the array get reduced to a single value?
AStep 1 (Map)
BStep 2 (Filter)
CStep 3 (Reduce)
DStep 4 (End)
💡 Hint
Look at execution_table row 3 where output is a single number.
If the filter condition changed to keep only numbers greater than 5, what would be the output after filter?
A[2, 4]
B[6, 8, 10]
C[1, 2, 3]
D[]
💡 Hint
Check variable_tracker 'doubled' after map and apply new filter condition.
Concept Snapshot
Map, filter, reduce are array helpers.
Map changes each element.
Filter keeps elements matching a test.
Reduce combines all into one value.
Use them to write clear, simple code.
Full Transcript
We start with an array of numbers. First, map multiplies each number by 2, creating a new array. Then, filter keeps only even numbers, which in this case are all of them. Finally, reduce adds all numbers together to get the sum. Variables change step-by-step but original array stays the same. This pattern helps process data clearly and efficiently.

Practice

(1/5)
1. What does the map function do in Swift when applied to an array?
easy
A. It changes each item in the array based on a rule.
B. It removes items that don't match a condition.
C. It combines all items into a single value.
D. It sorts the array in ascending order.

Solution

  1. Step 1: Understand the purpose of map

    The map function applies a transformation to each element in the array, creating a new array with the changed items.
  2. Step 2: Compare with other functions

    Unlike filter which removes items, or reduce which combines items, map changes each item individually.
  3. Final Answer:

    It changes each item in the array based on a rule. -> Option A
  4. Quick Check:

    map = change each item [OK]
Hint: Map transforms every item, filter picks, reduce combines [OK]
Common Mistakes:
  • Confusing map with filter or reduce
  • Thinking map removes items
  • Assuming map combines items into one
2. Which of the following is the correct syntax to use filter on an array numbers to keep only even numbers?
easy
A. let evens = numbers.map { $0 % 2 == 0 }
B. let evens = numbers.filter($0 % 2 == 0)
C. let evens = numbers.reduce(0) { $0 % 2 == 0 }
D. let evens = numbers.filter { $0 % 2 == 0 }

Solution

  1. Step 1: Identify correct filter syntax

    The filter method uses a closure with a condition inside curly braces, like { $0 % 2 == 0 }, to keep items matching the condition.
  2. Step 2: Check each option

    let evens = numbers.filter { $0 % 2 == 0 } correctly uses filter with the closure. let evens = numbers.map { $0 % 2 == 0 } uses map which changes items, not filters. let evens = numbers.reduce(0) { $0 % 2 == 0 } misuses reduce. let evens = numbers.filter($0 % 2 == 0) misses the closure braces.
  3. Final Answer:

    let evens = numbers.filter { $0 % 2 == 0 } -> Option D
  4. Quick Check:

    filter syntax = filter { condition } [OK]
Hint: Filter needs braces and a condition inside { } [OK]
Common Mistakes:
  • Using map instead of filter
  • Omitting braces in closure
  • Using reduce incorrectly for filtering
3. What is the output of this Swift code?
let numbers = [1, 2, 3, 4]
let result = numbers.reduce(0) { $0 + $1 }
print(result)
medium
A. 0
B. [1, 2, 3, 4]
C. 10
D. Error

Solution

  1. Step 1: Understand reduce with initial value 0

    The reduce starts with 0 and adds each number in the array: 0 + 1 + 2 + 3 + 4.
  2. Step 2: Calculate the sum

    Adding all numbers: 0 + 1 = 1, 1 + 2 = 3, 3 + 3 = 6, 6 + 4 = 10.
  3. Final Answer:

    10 -> Option C
  4. Quick Check:

    Sum of [1,2,3,4] = 10 [OK]
Hint: Reduce with + sums all items starting from initial value [OK]
Common Mistakes:
  • Confusing reduce with map or filter output
  • Forgetting initial value in reduce
  • Expecting array output instead of single value
4. Identify the error in this Swift code snippet:
let words = ["apple", "banana", "cherry"]
let filtered = words.filter { word in
    word.count > 5
}
print(filtered)
medium
A. No error, code runs correctly
B. Incorrect use of filter instead of map
C. Using word.count instead of word.length
D. Missing return keyword inside filter closure

Solution

  1. Step 1: Check filter closure syntax

    The closure uses implicit return because it is a single expression, so no explicit return is needed.
  2. Step 2: Verify property usage

    word.count is the correct way to get string length in Swift, so no error there.
  3. Final Answer:

    No error, code runs correctly -> Option A
  4. Quick Check:

    Single-expression closures return implicitly [OK]
Hint: Single-expression closures return automatically, no return needed [OK]
Common Mistakes:
  • Adding unnecessary return keyword
  • Confusing count with length property
  • Thinking filter needs map syntax
5. Given an array of integers, how would you use map, filter, and reduce together to find the sum of squares of only the odd numbers? Choose the correct Swift code.
hard
A. let sum = numbers.map { $0 * $0 }.filter { $0 % 2 != 0 }.reduce(0, +)
B. let sum = numbers.filter { $0 % 2 != 0 }.map { $0 * $0 }.reduce(0, +)
C. let sum = numbers.reduce(0) { $0 + $1 * $1 }
D. let sum = numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)

Solution

  1. Step 1: Filter odd numbers first

    We want only odd numbers, so use filter { $0 % 2 != 0 } to keep them.
  2. Step 2: Map to square each odd number

    Use map { $0 * $0 } to get squares of the filtered odd numbers.
  3. Step 3: Reduce to sum all squares

    Use reduce(0, +) to add all squared values into one sum.
  4. Final Answer:

    let sum = numbers.filter { $0 % 2 != 0 }.map { $0 * $0 }.reduce(0, +) -> Option B
  5. Quick Check:

    Filter odds, map squares, reduce sum [OK]
Hint: Filter odds first, then map squares, finally reduce sum [OK]
Common Mistakes:
  • Mapping before filtering odd numbers
  • Filtering even numbers by mistake
  • Using reduce without mapping squares
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard