Swift Array

🚀 Swift Array (Advanced) – Deep Dive for Interviews & Real Projects
This guide covers advanced Array concepts in Swift that are commonly asked in interviews and used in production apps.
1️⃣ Array Initialization – Advanced Ways ⭐
Output
2️⃣ Type Inference vs Explicit Type ⭐⭐
📌 Use explicit types when array starts empty.
3️⃣ Array Mutability (var vs let) ⭐⭐
📌 let arrays are immutable.
4️⃣ Safe Index Access (Very Important) ⭐⭐⭐
❌ Unsafe (can crash):
✔ Safe way:
5️⃣ Adding & Removing Elements ⭐⭐
Result
6️⃣ Slicing Arrays ⭐⭐⭐
Output
📌 Result type is ArraySlice<Int>
✔ Convert back to Array:
7️⃣ Enumerated Array (Index + Value) ⭐⭐
Output
8️⃣ Higher-Order Functions ⭐⭐⭐ (Interview Favorite)
map
Output-1:
filter
Output-2:
reduce
Output-3:
compactMap
Output-4:
flatMap
Output-5:
9️⃣ Sorting Arrays ⭐⭐
Output-6:
📌 sorted() → returns new array
📌 sort() → modifies original
🔟 Searching in Array ⭐⭐
1️⃣1️⃣ Remove Duplicates ⭐⭐⭐
📌 Order is not guaranteed.
1️⃣2️⃣ Performance Tip (Copy-on-Write) ⭐⭐⭐
📌 Swift uses Copy-on-Write (CoW) for efficiency.
1️⃣3️⃣ Common Mistakes ❌
❌ Index out of range
❌ Modifying let arrays
❌ Misusing map instead of forEach
❌ Ignoring optional results
📌 Interview Questions (Advanced Arrays)
Q1. Difference between map and compactMap?
👉 compactMap removes nil values
Q2. What is Copy-on-Write?
👉 Copy happens only on modification
Q3. Difference between sorted() and sort()?
👉 New array vs in-place sort
Q4. How to safely access array index?
👉 Use indices.contains()
✅ Summary
✔ Arrays are value types
✔ var → mutable, let → immutable
✔ Safe indexing prevents crashes
✔ map, filter, reduce are must-know
✔ Copy-on-Write improves performance
✔ Essential for Swift interviews & apps
