Swift map filter and reduce

🔬 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 ⭐
| Function | Purpose |
|---|---|
map | Transform elements |
filter | Select elements |
reduce | Combine elements into one |
2️⃣ map – Advanced Usage ⭐⭐⭐
Transform Model Objects
Output
map vs compactMap ⭐⭐⭐
Output:
📌 compactMap removes nil.
3️⃣ filter – Complex Conditions ⭐⭐⭐
Output
Filtering Custom Objects
4️⃣ reduce – Powerful Aggregations ⭐⭐⭐
Sum
Dictionary from Array
Output:
📌 reduce(into:) is more efficient.
5️⃣ Chaining Functions ⭐⭐⭐ (Interview Favorite)
Output
6️⃣ flatMap vs compactMap ⭐⭐⭐
Output:
7️⃣ Performance & Laziness ⭐⭐⭐
Using lazy
📌 Stops processing early → performance gain
8️⃣ Side Effects: forEach vs map ⚠️
❌ Wrong:
✔ Correct:
📌 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
