0
0
Swiftprogramming~10 mins

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

Choose your learning style9 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.