Chapter 67: Swift map, filter, reduce

1. The Big Picture – Why do we need map, filter, reduce?

These three functions are the core tools for working with collections in a functional, declarative style.

They allow you to:

  • transform every element → map
  • select only some elements → filter
  • combine all elements into one value → reduce

Together they replace most of the old-style loops with for and var result = ….

Golden rule used by almost every modern Swift developer:

Whenever you want to create a new collection from an existing one → prefer map / filter / compactMap / flatMap over manual for loops

2. map – transform every element

map creates a new array by applying the same transformation to every element of the original collection.

Swift

Realistic examples

Swift

Common real-life use-cases for map:

  • Convert data models to view models
  • Format numbers/dates for display
  • Transform API response into domain models
  • Prepare data for UI (add prefixes, icons, colors…)

3. filter – select only some elements

filter creates a new array containing only the elements that satisfy a condition.

Swift

Realistic examples

Swift

Common real-life use-cases for filter:

  • Show only active users / visible items
  • Filter products by price/category/availability
  • Keep only valid form fields / search results
  • Remove nil / invalid entries (combine with compactMap)

4. reduce – combine all elements into one value

reduce takes all elements and accumulates them into a single result.

Swift

Realistic examples

Swift

Common real-life use-cases for reduce:

  • Calculate sum, average, max, min
  • Build a string (CSV line, concatenated names)
  • Accumulate stats (total price, word count, score sum)
  • Combine objects (merge dictionaries, combine permissions)

5. Very Common Real-Life Combined Example (map + filter + reduce)

Swift

Alternative readable style (often preferred in teams):

Swift

6. Very Common Beginner Mistakes & Correct Habits

Mistake Wrong / Dangerous code Correct / Better habit Why?
Mutating original array inside map/filter numbers.map { numbers.append($0 * 2) } Never mutate original inside transformation Runtime error or unexpected behavior
Force-unwrapping inside map array.map { $0! } Use compactMap for optionals Crash if any nil
Using reduce for simple sum reduce(0) { $0 + $1 } reduce(0, +) Shorter & clearer
Confusing map and forEach array.map { print($0) } Use forEach for side-effects map should return transformed values
Forgetting map/filter create new arrays array.map { $0 * 2 } then expect original changed Understand map/filter/reduce return new values Original array stays unchanged

7. Quick Reference – Most Used Patterns

Goal Most idiomatic code Notes / Tip
Transform every element array.map { … } Returns new array
Keep only some elements array.filter { $0 > 10 } Returns new array
Convert optionals & remove nil array.compactMap { $0 } Removes nil, unwraps
Flatten nested arrays array.flatMap { $0 } Turns [[1,2],[3,4]] → [1,2,3,4]
Sum / average / max array.reduce(0, +) or array.reduce(0.0) { $0 + $1 } reduce(into:) variant also very popular
Build string from elements array.map(String.init).joined(separator: “, “) Very frequent for CSV, logs

8. Small Practice – Try these

  1. Create array of 6 numbers → Use map to multiply each by 3 → Use filter to keep only numbers > 15 → Use reduce to calculate their sum
  2. Create array of 5 names → Use map to capitalize each name → Use filter to keep only names longer than 5 letters → Use joined to make one comma-separated string
  3. Create array of optional Ints [Int?] = [1, nil, 3, nil, 5] → Use compactMap to get [1,3,5] → Sum them with reduce

Paste your code here if you want feedback or want to see more elegant versions!

What would you like to explore next?

  • compactMap, flatMap, reduce(into:) in depth
  • Combining map + filter + reduce chains
  • forEach vs for-in vs map decision guide
  • Collections in SwiftUI (List, ForEach, @State)
  • Or move to another topic (dictionaries, sets, optionals, switch…)

Just tell me — we’ll continue in the same clear, patient, detailed style 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *