Implementing Hashable protocol

suggest change

Types used as Set elements and Dictionary keys must conform to the Hashable protocol, which inherits from the Equatable protocol.

A custom type that conforms to Hashable must provide a hashValue property. Equatable requires ==; != has a default implementation, so it does not need to be written. Swift 4.2 and later synthesize Hashable for many structs and prefer hash(into:) over hashValue.

The following example implements Hashable for a custom struct:

struct Cell {
    var row: Int
    var col: Int
    
    init(_ row: Int, _ col: Int) {
        self.row = row
        self.col = col
    }
}

extension Cell: Hashable {
    
    // Satisfy Hashable requirement
    var hashValue: Int {
        get {
            return row.hashValue^col.hashValue
        }
    }

    // Satisfy Equatable requirement
    static func ==(lhs: Cell, rhs: Cell) -> Bool {
        return lhs.col == rhs.col && lhs.row == rhs.row
    }
    
}

// Cell can now be a dictionary key
var dict = [Cell : String]()

dict[Cell(0, 0)] = "0, 0"
dict[Cell(1, 0)] = "1, 0"
dict[Cell(0, 1)] = "0, 1"

// Also we can create Set of Cells
var set = Set<Cell>()

set.insert(Cell(0, 0))
set.insert(Cell(1, 0))

Note: Different values of a custom type do not need different hash values; collisions are acceptable. When hash values are equal, == determines real equality.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents