Swift Dictionary

Swift Tutorial

📘 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.

var marks = ["Math": 90, "Science": 85]
  • Keys are unique

  • Values can be duplicated

  • Dictionaries are unordered


2️⃣ Dictionary Initialization – Advanced Ways ⭐


 

Using Dictionary(uniqueKeysWithValues:)


 

Output:

["A": 1, "B": 2]

3️⃣ Accessing Values Safely ⭐⭐⭐

❌ Unsafe (can crash if key not found):

print(marks["Math"]!)

✔ Safe way:

if let value = marks["Math"] {
print(value)
}

✔ With default value:

print(marks["English", default: 0])

4️⃣ Adding, Updating & Removing Values ⭐⭐


 

Result:

["A": 95, "C": 85]

5️⃣ Looping Through Dictionary ⭐⭐

Key–Value Loop


 


Keys Only


 


Values Only


 


6️⃣ Dictionary map, filter, reduce ⭐⭐⭐ (Interview Favorite)

map


 

Output-1:

[("A", 190), ("C", 170)]

filter


 

Output-2:

["A": 95]

reduce


 

Output-3:

180

7️⃣ Transform Dictionary Values ⭐⭐


 

Output-4:

["A": 100, "C": 90]

📌 Keys remain unchanged.


8️⃣ Sorting Dictionary ⭐⭐⭐

Sort by Key


 


Sort by Value


 

📌 Result type: [(key: String, value: Int)]


9️⃣ Merging Dictionaries ⭐⭐


 

let merged = d1.merging(d2) { old, new in new }

Output-5:

["A": 1, "B": 3, "C": 4]

🔟 Dictionary with Custom Types ⭐⭐⭐


 


1️⃣1️⃣ Performance & Internals ⭐⭐⭐

  • Dictionaries are value types

  • Use Copy-on-Write (CoW)

  • Copy happens only when modified

var d1 = ["A": 1]
var d2 = d1 // no copy yet
d2["B"] = 2 // copy happens here

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

You may also like...