← Back to Swift Course | Chapter 6: Collections | Lesson 6 of 7

map, filter, and reduce

map changes every item in a list, filter picks out only the ones you want, and reduce combines them all into one single result.

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

markup
let numbers = [1, 2, 3, 4]
let squared = numbers.map { $0 * $0 }
print(squared)

Filtering with filter

.filter keeps only the elements for which the given closure returns true, discarding the rest.

Example: Filtering with filter

markup
let numbers = [1, 2, 3, 4, 5, 6]
let evens = numbers.filter { $0 % 2 == 0 }
print(evens)

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

markup
let prices = [9.99, 19.99, 5.00]
let total = prices.reduce(0) { partial, price in partial + price }
print("Total: \(total)")

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

markup
let numbers = [1, 2, 3, 4, 5, 6, 7, 8]
let sumOfSquaredEvens = numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)
print(sumOfSquaredEvens)
Common Mistakes
  1. Using a manual for loop to transform every element when .map() expresses the same intent more clearly and concisely.
  2. Forgetting that .filter()'s closure must return a Bool deciding whether to keep each element.
  3. Misunderstanding .reduce()'s first argument as the final result instead of the starting accumulator value.
Chapter Summary
  • .map { } transforms each element and returns a new array of the results.
  • .filter { } keeps only elements for which the closure returns true.
  • .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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.