100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Swift

Dictionaries and Sets in Swift

Understand Swift's key-value dictionaries and unique-element sets, including how Hashable powers both.

CollectionsBeginner9 min readJul 8, 2026
Analogies

Introduction

Dictionaries store key-value pairs where each key is unique, letting you look up a value quickly by its associated key. Sets store unique elements with no defined order and no associated values. Both collections require their key or element type to conform to the Hashable protocol, which lets Swift use a hash-based structure internally for fast lookups, insertions, and removals rather than scanning the whole collection.

🏏

Cricket analogy: A scorecard is like a dictionary: each player's name is a unique key mapping to their runs, so you look up Kohli's score instantly instead of scanning every entry on the sheet.

Syntax

swift
var dict: [String: Int] = ["a": 1, "b": 2]
var mySet: Set<Int> = [1, 2, 3]
var emptyDict: [String: String] = [:]
var emptySet = Set<String>()

Explanation

Both dictionaries and sets are unordered — iterating over them does not guarantee any particular sequence. Subscript access on a dictionary, such as dict["a"], always returns an Optional value (Int? in this example) because the key might not exist; this forces you to safely unwrap the result with optional binding or nil-coalescing rather than assuming presence. Sets are ideal for fast membership checks (.contains()) and support classic set algebra operations like .union(_:) to combine two sets, .intersection(_:) to find common elements, and .subtracting(_:) to remove elements found in another set.

🏏

Cricket analogy: Checking if Root is in today's playing XI is a .contains() set check, while .intersection() finds players who featured in both this Ashes and the last one, and squad["Root"] returns an optional since he might be rested.

Example

swift
var ages: [String: Int] = ["Alice": 30, "Bob": 25]
ages["Carol"] = 40
let aliceAge: Int? = ages["Alice"]
print(aliceAge ?? -1)
print(ages["Dave"] ?? -1)

let setA: Set<Int> = [1, 2, 3]
let setB: Set<Int> = [2, 3, 4]
print(setA.union(setB).sorted())
print(setA.intersection(setB).sorted())
print(setA.subtracting(setB).sorted())

Output

swift
30
-1
[1, 2, 3, 4]
[2, 3]
[1]

Key Takeaways

  • Dictionaries store unordered key-value pairs; keys must be Hashable and unique.
  • Subscripting a dictionary always returns an Optional value.
  • Sets store unordered, unique elements and require Hashable elements.
  • Sets excel at fast membership checks with .contains().
  • .union, .intersection, and .subtracting implement classic set algebra.

Practice what you learned

Was this page helpful?

Topics covered

#Swift#SwiftProgrammingStudyNotes#Programming#DictionariesAndSetsInSwift#Dictionaries#Sets#Syntax#Explanation#DataStructures#StudyNotes#SkillVeris