Swift map filter and reduce

Swift Tutorial

🔬 Swift map filter and reduce (Advanced) – Interview & Production Deep Dive

In Swift map filter and reduce are higher-order functions that enable functional programming in Swift.
They are heavily tested in interviews and used widely in real-world Swift apps.


1️⃣ Quick Concept Recap ⭐

FunctionPurpose
mapTransform elements
filterSelect elements
reduceCombine elements into one

2️⃣ map – Advanced Usage ⭐⭐⭐

Transform Model Objects


 

Output

["Amit", "Neha"]

map vs compactMap ⭐⭐⭐


 

Output:

mapped → [Optional(1), nil, Optional(3)]
compact → [1, 3]

📌 compactMap removes nil.


3️⃣ filter – Complex Conditions ⭐⭐⭐


 

Output

[20, 30]

Filtering Custom Objects



4️⃣ reduce – Powerful Aggregations ⭐⭐⭐

Sum

let sum = numbers.reduce(0) { $0 + $1 }

Dictionary from Array


 

Output:

["apple": 2, "banana": 1]

📌 reduce(into:) is more efficient.


5️⃣ Chaining Functions ⭐⭐⭐ (Interview Favorite)


 

Output

130

6️⃣ flatMap vs compactMap ⭐⭐⭐


 

Output:

[1, 2, 3, 4]

7️⃣ Performance & Laziness ⭐⭐⭐

Using lazy


📌 Stops processing early → performance gain


8️⃣ Side Effects: forEach vs map ⚠️

Wrong:

numbers.map { print($0) }

Correct:

numbers.forEach { print($0) }

📌 map should return values, not side effects.


9️⃣ Common Interview Pitfalls ❌

❌ Using map instead of forEach
❌ Forgetting compactMap for optionals
❌ Using reduce when simple loop is clearer
❌ Ignoring performance for large collections


🔥 Interview Questions (Advanced)

Q1. Difference between map and compactMap?
👉 compactMap removes nil

Q2. When to use reduce(into:)?
👉 When mutating accumulator efficiently

Q3. What does lazy do?
👉 Delays execution until needed

Q4. Can these replace loops?
👉 Often yes, but not always


✅ Summary

map transforms
filter selects
reduce aggregates
compactMap removes nil
✔ Chaining enables clean logic
lazy improves performance
✔ Core for Swift functional programming & interviews

You may also like...