Swift Dictionaries and Sets

Swift provides three main collection types: arrays, dictionaries, and sets. This topic covers the latter two. A dictionary stores key-value pairs, and a set stores unique values with no defined order.

Dictionaries – The Phone Book Analogy


┌────────────────────────────────────────────────┐
│  Dictionary = Phone Book                       │
│                                                │
│  Key (Name)    →  Value (Number)               │
│  "Rahul"       →  "9876543210"                 │
│  "Sneha"       →  "8765432109"                 │
│  "Vikram"      →  "7654321098"                 │
│                                                │
│  You look up a name (key) to find a            │
│  phone number (value).                         │
└────────────────────────────────────────────────┘

Creating a Dictionary

var capitals: [String: String] = [
    "India": "New Delhi",
    "Japan": "Tokyo",
    "France": "Paris"
]

// Empty dictionary
var scores = [String: Int]()

Reading Values

let city = capitals["India"]
print(city ?? "Not found")   // New Delhi

// Direct access returns an Optional
let unknown = capitals["Brazil"]
print(unknown ?? "Not found")   // Not found

Dictionary lookups return an optional because the key might not exist. Always use ?? or optional binding to handle a missing key safely.

Adding and Updating

capitals["Germany"] = "Berlin"      // adds new pair
capitals["Japan"] = "Kyoto"         // updates existing value
print(capitals["Japan"] ?? "")      // Kyoto

Removing a Key

capitals["France"] = nil            // removes France
capitals.removeValue(forKey: "Germany")

Iterating Over a Dictionary

for (country, capital) in capitals {
    print("\(country): \(capital)")
}

// Keys and values separately
print(capitals.keys)
print(capitals.values)

Dictionary order is not guaranteed — items may print in any sequence each time. If order matters, sort the keys first.

Dictionary Properties

print(capitals.count)     // number of pairs
print(capitals.isEmpty)   // false

Sets – The Unique Guest List Analogy


┌────────────────────────────────────────────────┐
│  Set = A guest list with no duplicates         │
│                                                │
│  You invite: Alice, Bob, Alice, Charlie        │
│  Guest list: {Alice, Bob, Charlie}             │
│                                                │
│  The second "Alice" is ignored.                │
│  Every name appears exactly once.              │
└────────────────────────────────────────────────┘

Creating a Set

var tags: Set<String> = ["swift", "ios", "apple"]
var numbers: Set = [1, 2, 3, 2, 1]
print(numbers)   // {1, 2, 3}  — duplicates removed

Adding and Removing

tags.insert("xcode")
tags.remove("apple")
print(tags.contains("ios"))   // true

Set Operations – The Venn Diagram

let setA: Set = [1, 2, 3, 4, 5]
let setB: Set = [4, 5, 6, 7, 8]

print(setA.union(setB))              // {1,2,3,4,5,6,7,8}
print(setA.intersection(setB))       // {4,5}
print(setA.subtracting(setB))        // {1,2,3}
print(setA.symmetricDifference(setB))// {1,2,3,6,7,8}

┌────────────────────────────────────────────────┐
│  Set A        Both       Set B                 │
│  [1, 2, 3] [4, 5]    [6, 7, 8]                 │
│                                                │
│  union         → all elements together         │
│  intersection  → only shared elements          │
│  subtracting   → A minus what B has            │
│  symmetricDiff → everything NOT shared         │
└────────────────────────────────────────────────┘

Dictionary vs Array vs Set – Quick Comparison

FeatureArrayDictionarySet
OrderOrderedUnorderedUnordered
Access byIndexKeyValue
DuplicatesAllowedKeys uniqueNot allowed
Best forListsLookup tablesUnique items

Leave a Comment

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