Swift Dictionary

📘 Swift Dictionary (Advanced) – Deep Dive for Interviews & Real Projects
This guide covers advanced Dictionary concepts in Swift that are frequently asked in interviews and used in production apps.
1️⃣ Dictionary Basics (Quick Recap)
A Dictionary stores data in key–value pairs.
Keys are unique
Values can be duplicated
Dictionaries are unordered
2️⃣ Dictionary Initialization – Advanced Ways ⭐
Using Dictionary(uniqueKeysWithValues:)
Output:
3️⃣ Accessing Values Safely ⭐⭐⭐
❌ Unsafe (can crash if key not found):
✔ Safe way:
✔ With default value:
4️⃣ Adding, Updating & Removing Values ⭐⭐
Result:
5️⃣ Looping Through Dictionary ⭐⭐
Key–Value Loop
Keys Only
Values Only
6️⃣ Dictionary map, filter, reduce ⭐⭐⭐ (Interview Favorite)
map
Output-1:
filter
Output-2:
reduce
Output-3:
7️⃣ Transform Dictionary Values ⭐⭐
Output-4:
📌 Keys remain unchanged.
8️⃣ Sorting Dictionary ⭐⭐⭐
Sort by Key
Sort by Value
📌 Result type: [(key: String, value: Int)]
9️⃣ Merging Dictionaries ⭐⭐
Output-5:
🔟 Dictionary with Custom Types ⭐⭐⭐
1️⃣1️⃣ Performance & Internals ⭐⭐⭐
Dictionaries are value types
Use Copy-on-Write (CoW)
Copy happens only when modified
1️⃣2️⃣ Common Mistakes ❌
❌ Force-unwrapping values
❌ Expecting sorted order
❌ Modifying dictionary during iteration
❌ Using dictionary instead of array/set
📌 Interview Questions (Swift Dictionary – Advanced)
Q1. Are Swift dictionaries ordered?
👉 No
Q2. What is mapValues()?
👉 Transforms values while keeping keys
Q3. How to safely access dictionary value?
👉 Optional binding or default value
Q4. What happens when keys collide during merge?
👉 Conflict closure decides
✅ Summary
✔ Dictionary stores key–value pairs
✔ Keys must be unique
✔ Safe access is critical
✔ map, filter, reduce are must-know
✔ mapValues() for value transformation
✔ Copy-on-Write improves performance
✔ Very important for Swift interviews
