What if you could turn messy loops into clean, powerful one-liners that do the work for you?
Why Map, filter, reduce patterns in Swift? - Purpose & Use Cases
Imagine you have a long list of numbers and you want to find all the even ones, double them, and then add them all up. Doing this by hand means writing lots of loops and checks, which can get confusing fast.
Manually looping through each item, checking conditions, and keeping track of totals is slow and easy to mess up. One missed step or wrong calculation can break the whole result, making your code hard to read and fix.
Map, filter, and reduce let you handle these tasks in clear, simple steps. You can filter the list to keep only even numbers, map to double them, and reduce to sum them up--all in a neat, readable way.
var sum = 0 for number in numbers { if number % 2 == 0 { sum += number * 2 } }
let sum = numbers.filter { $0 % 2 == 0 }
.map { $0 * 2 }
.reduce(0, +)It makes your code easier to write, read, and maintain while handling complex data tasks smoothly.
Think about filtering a list of products to find only those on sale, adjusting their prices, and then calculating the total discount--all done cleanly with these patterns.
Manual loops are slow and error-prone.
Map, filter, reduce break tasks into clear steps.
They make code simpler and more reliable.
Practice
map function do in Swift when applied to an array?Solution
Step 1: Understand the purpose of map
Themapfunction applies a transformation to each element in the array, creating a new array with the changed items.Step 2: Compare with other functions
Unlikefilterwhich removes items, orreducewhich combines items,mapchanges each item individually.Final Answer:
It changes each item in the array based on a rule. -> Option AQuick Check:
map = change each item [OK]
- Confusing map with filter or reduce
- Thinking map removes items
- Assuming map combines items into one
filter on an array numbers to keep only even numbers?Solution
Step 1: Identify correct filter syntax
Thefiltermethod uses a closure with a condition inside curly braces, like{ $0 % 2 == 0 }, to keep items matching the condition.Step 2: Check each option
let evens = numbers.filter { $0 % 2 == 0 } correctly usesfilterwith the closure. let evens = numbers.map { $0 % 2 == 0 } usesmapwhich changes items, not filters. let evens = numbers.reduce(0) { $0 % 2 == 0 } misusesreduce. let evens = numbers.filter($0 % 2 == 0) misses the closure braces.Final Answer:
let evens = numbers.filter { $0 % 2 == 0 } -> Option DQuick Check:
filter syntax = filter { condition } [OK]
- Using map instead of filter
- Omitting braces in closure
- Using reduce incorrectly for filtering
let numbers = [1, 2, 3, 4]
let result = numbers.reduce(0) { $0 + $1 }
print(result)Solution
Step 1: Understand reduce with initial value 0
Thereducestarts with 0 and adds each number in the array: 0 + 1 + 2 + 3 + 4.Step 2: Calculate the sum
Adding all numbers: 0 + 1 = 1, 1 + 2 = 3, 3 + 3 = 6, 6 + 4 = 10.Final Answer:
10 -> Option CQuick Check:
Sum of [1,2,3,4] = 10 [OK]
- Confusing reduce with map or filter output
- Forgetting initial value in reduce
- Expecting array output instead of single value
let words = ["apple", "banana", "cherry"]
let filtered = words.filter { word in
word.count > 5
}
print(filtered)Solution
Step 1: Check filter closure syntax
The closure uses implicit return because it is a single expression, so no explicitreturnis needed.Step 2: Verify property usage
word.countis the correct way to get string length in Swift, so no error there.Final Answer:
No error, code runs correctly -> Option AQuick Check:
Single-expression closures return implicitly [OK]
- Adding unnecessary return keyword
- Confusing count with length property
- Thinking filter needs map syntax
map, filter, and reduce together to find the sum of squares of only the odd numbers?
Choose the correct Swift code.Solution
Step 1: Filter odd numbers first
We want only odd numbers, so usefilter { $0 % 2 != 0 }to keep them.Step 2: Map to square each odd number
Usemap { $0 * $0 }to get squares of the filtered odd numbers.Step 3: Reduce to sum all squares
Usereduce(0, +)to add all squared values into one sum.Final Answer:
let sum = numbers.filter { $0 % 2 != 0 }.map { $0 * $0 }.reduce(0, +) -> Option BQuick Check:
Filter odds, map squares, reduce sum [OK]
- Mapping before filtering odd numbers
- Filtering even numbers by mistake
- Using reduce without mapping squares
Ready to prove it?
Pass the test and this pattern moves unknown
