Swift Academy · Lesson

Hashable and hash(into:)

Enable use as dictionary keys and set members.

Lesson 2 of 413 steps

Hashable and hash(into:) is a free Swift Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.

What Is Hashable?

Hashable builds on Equatable and provides a hash value. It is required to use a type as a Set element or a Dictionary key.

Automatic Hashable

Like Equatable, structs and enums with Hashable members get it synthesized:

struct Point: Hashable {
    let x: Int
    let y: Int
}
let set: Set<Point> = [Point(x: 0, y: 0), Point(x: 0, y: 0)]
print(set.count)  // 1  -- duplicate collapsed

Using a Type as a Dictionary Key

Hashable types can key a dictionary:

struct Coord: Hashable { let r: Int; let c: Int }
var grid: [Coord: String] = [:]
grid[Coord(r: 0, c: 0)] = "start"
print(grid[Coord(r: 0, c: 0)]!)  // "start"

The Hashable Contract

Two values that are equal (==) MUST produce the same hash. If you customize one, keep both consistent or sets and dictionaries will misbehave.

Custom hash(into:)

Implement hash(into:) by feeding the relevant properties into the hasher:

struct User: Hashable {
    let id: Int
    let name: String
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
    static func == (l: User, r: User) -> Bool { l.id == r.id }
}
print(Set([User(id: 1, name: "A"), User(id: 1, name: "B")]).count)  // 1

Combining Multiple Fields

Feed every field that participates in equality:

struct Pair: Hashable {
    let a: Int
    let b: String
    func hash(into hasher: inout Hasher) {
        hasher.combine(a)
        hasher.combine(b)
    }
}
print(Pair(a: 1, b: "x").hashValue == Pair(a: 1, b: "x").hashValue)  // true

Why Only Identity Fields

Hash only the fields used in ==. Including extra (mutable) fields can break the equal-implies-same-hash rule:

struct Doc: Hashable {
    let id: Int       // identity
    var title: String // not part of equality
    func hash(into hasher: inout Hasher) { hasher.combine(id) }
    static func == (l: Doc, r: Doc) -> Bool { l.id == r.id }
}
print(Doc(id: 1, title: "v1") == Doc(id: 1, title: "v2"))  // true

Hashable Enums

Enums are Hashable automatically (with associated values when those are Hashable):

enum Direction: Hashable { case north, south, east, west }
let visited: Set<Direction> = [.north, .north, .east]
print(visited.count)  // 2

Deduplicating with a Set

A common use: remove duplicates by going through a Set:

let nums = [1, 2, 2, 3, 3, 3]
let unique = Array(Set(nums)).sorted()
print(unique)  // [1, 2, 3]

Hasher Is Per-Run Randomized

Hash values are seeded per program run, so never persist a hashValue to disk or rely on its exact number across launches:

struct K: Hashable { let v: Int }
let h1 = K(v: 5).hashValue
// h1 is stable within this run only
print(K(v: 5) == K(v: 5))  // true  -- equality is what to rely on

Counting with a Dictionary

Hashable keys power frequency counts — a very common pattern:

let letters = ["a", "b", "a", "c", "b", "a"]
var counts: [String: Int] = [:]
for l in letters { counts[l, default: 0] += 1 }
print(counts["a"]!)  // 3

Quick Check

What rule must hash(into:) respect relative to ==?

Recap

You learned Hashable:

  • Hashable refines Equatable, required for Set/Dictionary keys
  • Synthesized for structs/enums with Hashable members
  • Custom hash(into:) — combine only the identity fields used in ==
  • Equal values must hash equally; hashes are per-run randomized

Next: Comparable and sorting.

Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

Is the “Hashable and hash(into:)” lesson free?

Yes — any 3 lessons of the Swift Academy learning path, including “Hashable and hash(into:)”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.

What will I learn in “Hashable and hash(into:)”?

Enable use as dictionary keys and set members. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Hashable and hash(into:)” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Synthesized Equatable
  2. Hashable and hash(into:)
  3. Comparable and Sorting
  4. Custom Equality Semantics
← Back to Swift Academy