Swift Array

Swift Tutorial

🚀 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

[0, 0, 0, 0, 0]

2️⃣ Type Inference vs Explicit Type ⭐⭐

📌 Use explicit types when array starts empty.


3️⃣ Array Mutability (var vs let) ⭐⭐

var arr1 = [1, 2, 3]
arr1.append(4) // ✅ allowed
let arr2 = [1, 2, 3]
// arr2.append(4) ❌ error

📌 let arrays are immutable.


4️⃣ Safe Index Access (Very Important) ⭐⭐⭐

❌ Unsafe (can crash):

print(arr1[10])

✔ Safe way:

if arr1.indices.contains(2) {
print(arr1[2])
}

5️⃣ Adding & Removing Elements ⭐⭐


 

Result

[0, 3]

6️⃣ Slicing Arrays ⭐⭐⭐


 

Output

[20, 30, 40]

📌 Result type is ArraySlice<Int>

✔ Convert back to Array:

let newArr = Array(slice)

7️⃣ Enumerated Array (Index + Value) ⭐⭐


 

Output

0 Apple
1 Banana
2 Mango

8️⃣ Higher-Order Functions ⭐⭐⭐ (Interview Favorite)

map


 

Output-1:

[1, 4, 9]

filter


Output-2:

[2]

reduce


 

Output-3:

6

compactMap


 

Output-4:

[1, 3]

flatMap


 

Output-5:

[1, 2, 3, 4]

9️⃣ Sorting Arrays ⭐⭐


 

Output-6:

[4, 3, 2, 1]

📌 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

You may also like...