liveBook · Manning

Hashable

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

Hashable is a Swift protocol for types whose values can be represented by hash values for hashed collection membership and lookup.

Hashable is a Swift protocol for values that can serve as keys in hashed collections. In maze search, a location must be stored in a Set so the algorithm can track explored positions. A custom MazeLocation struct supplies that identity. section 2.2

Implement a hashable maze location by defining:

  • A struct containing row and column coordinates. section 2.2
  • Hashing that combines the row and column hash values. section 2.2
  • Equality that compares both coordinates; Hashable-conforming types must also implement ==. section 2.2

Maze locations

struct MazeLocation: Hashable { let row: Int; let col: Int; var hashValue: Int { row.hashValue ^ col.hashValue } } Equality returns true only when both row and column match. The resulting values can populate the explored Set used by depth-first, breadth-first, and A* searches. section 2.2

struct MazeLocation: Hashable {
    let row: Int
    let col: Int
    var hashValue: Int { return row.hashValue ^ col.hashValue }
}

func == (lhs: MazeLocation, rhs: MazeLocation) -> Bool {
    return lhs.row == rhs.row && lhs.col == rhs.col
}

Inspect the complete MazeLocation definition, including coordinate storage, hashValue, and equality. section 2.2

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Defines a custom struct, hashValue, and equality, but does not explain hashing internals.
Examples
Uses MazeLocation row-column coordinates as the concrete Hashable example.
What it assumes
Assumes structs and operators, while demonstrating from the example why tuples cannot serve as Hashable maze keys.
What you can do after
Apply it by defining hashable coordinate values for explored-state tracking in Swift search algorithms.
How it connects
Connects Hashable with Set, equality, maze search, depth-first search, breadth-first search, and A*.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.