map, filter, and reduce
In this page:
let mapped = array.map { $0 transformation }
let filtered = array.filter { condition using $0 }
let total = array.reduce(initialValue) { partial, element in partial + element }
Transforming with map
.map applies a closure to every element and collects the results into a new array, without changing the original.
Example: Transforming with map
// Declare a constant `numbers`, set to `[1, 2, 3, 4]`
let numbers = [1, 2, 3, 4]
// Declare a constant `squared`, set to `numbers.map { $0 * $0 }`
let squared = numbers.map { $0 * $0 }
// Print `squared` to the console
print(squared)
Login to try C/C++/Java/PHP code in the editor
Filtering with filter
.filter keeps only the elements for which the given closure returns true, discarding the rest.
Example: Filtering with filter
// Declare a constant `numbers`, set to `[1, 2, 3, 4, 5, 6]`
let numbers = [1, 2, 3, 4, 5, 6]
// Declare a constant `evens`, set to `numbers.filter { $0 % 2 == 0 }`
let evens = numbers.filter { $0 % 2 == 0 }
// Print `evens` to the console
print(evens)
Login to try C/C++/Java/PHP code in the editor
Combining with reduce
.reduce folds all elements into a single value, starting from an initial value and combining it with each element in turn.
Example: Combining with reduce
// Declare a constant `prices`, set to `[9.99, 19.99, 5.00]`
let prices = [9.99, 19.99, 5.00]
// Declare a constant `total`, set to `prices.reduce(0) { partial, price in partial + price }`
let total = prices.reduce(0) { partial, price in partial + price }
// Print "Total: \(total)" to the console
print("Total: \(total)")
Login to try C/C++/Java/PHP code in the editor
Chaining map, filter, and reduce
These operations can be chained together to express a multi-step transformation in a single readable pipeline.
Example: Chaining map, filter, and reduce
// Declare a constant `numbers`, set to `[1, 2, 3, 4, 5, 6, 7, 8]`
let numbers = [1, 2, 3, 4, 5, 6, 7, 8]
// Declare a constant `sumOfSquaredEvens`, set to `numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)`
let sumOfSquaredEvens = numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)
// Print `sumOfSquaredEvens` to the console
print(sumOfSquaredEvens)
Login to try C/C++/Java/PHP code in the editor
- Using a manual
forloop to transform every element when.map()expresses the same intent more clearly and concisely. - Forgetting that
.filter()'s closure must return aBooldeciding whether to keep each element. - Misunderstanding
.reduce()'s first argument as the final result instead of the starting accumulator value.
.map { }transforms each element and returns a new array of the results..filter { }keeps only elements for which the closure returnstrue..reduce(initial) { }combines all elements into a single accumulated value.- These three can be chained together for powerful, readable data transformations.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: