Chapter 66: Swift Dictionaries

1. What is a Dictionary in Swift? (the most important intuition)

A dictionary is a collection that stores key → value pairs.

You ask: “Give me the value associated with this key.”

It’s like:

  • a real-life dictionary (word → meaning)
  • a phone book (name → phone number)
  • user settings (setting name → value)
  • JSON data (field name → value)
  • a configuration object
  • a lookup table

The most important property of a dictionary:

You can very quickly find a value if you know its key (usually O(1) time — extremely fast, even with millions of items)

2. Basic syntax — the most common ways to create dictionaries

Swift

3. Reading, writing, updating, removing — the core operations

Swift

4. Real-life examples — dictionaries you will actually use

Example 1 — User profile / settings (extremely common)

Swift

Example 2 — Settings / preferences screen

Swift

Example 3 — JSON-like data / API response (very frequent)

Swift

5. Strongly typed dictionaries — modern & recommended style

Swift

Why this is better:

  • No magic strings → typos are caught at compile time
  • Auto-complete works
  • Refactoring is safe

6. Very Common Beginner Mistakes & Correct Habits

Mistake Wrong / Dangerous code Correct / Better habit Why?
Force-unwrapping dictionary values let name = dict[“name”] as! String let name = dict[“name”] as? String ?? “Guest” Missing key → crash
Using Any everywhere [String: Any] for everything Use concrete types or enum keys when possible Less safety, harder debugging
Assuming order in Dictionary for (k,v) in dict { print(k) } Never rely on order — use Array if order matters Dictionaries are unordered (or insertion order only)
Modifying while iterating for (k,v) in dict { dict[k] = … } Collect changes in new dict or use for key in dict.keys Runtime error: collection mutated
Checking existence incorrectly if dict[“key”] != nil { … } if dict.keys.contains(“key”) { … } or if let _ = dict[“key”] { … } More explicit

7. Quick Reference — Dictionary operations you will use every day

Goal Code example Returns / modifies original?
Read value safely dict[“key”] as? String ?? “default”
Update / add value dict[“key”] = newValue modifies original
Remove key dict[“key”] = nil modifies original
Check if key exists dict.keys.contains(“key”) or if let _ = dict[“key”] Bool
Loop over all pairs for (key, value) in dict { … }
Get all keys / values Array(dict.keys) / Array(dict.values) new arrays
Merge two dictionaries dict1.merge(dict2) { $1 } modifies dict1

8. Small Practice — Try these

  1. Create a dictionary for a user profile keys: name, age, city, isPremium, points → Print all key-value pairs → Change age to 25 → Add “favoriteColor”: “Blue”
  2. Create a settings dictionary keys: theme (“dark”/”light”), fontSize (16), notificationsEnabled (true) → Apply theme based on value → Print current font size
  3. Create dictionary from two arrays keys = [“name”, “score”, “rank”] values = [“Rahul”, 920, 5] → Print the resulting dictionary

Paste your code here if you want feedback or want to see more polished versions!

What would you like to explore next?

  • Dictionary with typed keys (enum-based — very modern & safe)
  • Default values & merging dictionaries
  • Nested dictionaries (JSON-like structures)
  • Sets in depth (uniqueness, fast lookup)
  • Array vs Set vs Dictionary decision guide
  • Collections in SwiftUI (List, ForEach, @State)

Just tell me — we’ll continue in the same clear, detailed, patient style 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *