Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 146 ยท Structures, Classes and Enums

Equatable, Hashable and Comparable

Learn Swift's Equatable, Hashable and Comparable protocols - synthesized conformances, custom ==, hash(into:), sorting custom types, Set and dictionary keys, and the rules that keep them correct.

Sooner or later you need to ask three questions about your own types. Are these two values the same? Can I use this as a dictionary key or put it in a set? Which one comes first when I sort? Swift answers them with three small protocols: Equatable, Hashable and Comparable. They form a ladder. Hashable builds on Equatable, and Comparable builds on Equatable as well.

The best part is that for most types you write almost no code. Add the protocol name to your declaration and the compiler synthesizes the implementation. This lesson shows when that works, how to write the methods by hand when it does not, and the laws that custom implementations must obey.

Equatable: the == operator

Conforming to Equatable gives your type the == and != operators. If every stored property is itself Equatable, the compiler writes == for you, comparing the properties one by one.

Swift Synthesized Equatable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is true, false, true, true and Optional(0). Because Point is Equatable, the array methods contains(_:) and firstIndex(of:) (which take a value, not a closure) become available. Enums without associated values are Equatable automatically, and enums with associated values synthesize it when you declare the conformance and every payload type is Equatable.

When synthesis is not enough

Synthesis compares everything. Sometimes that is wrong. A User might be "the same user" whenever the id matches, even if the display name has changed. Write == yourself as a static method.

Swift Custom ==

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

before == after prints true even though two fields differ, and before == other prints false even though the names match. That is what you asked for.

Custom == must respect three laws, or algorithms that rely on it will misbehave:

  1. Reflexive: a == a is always true.
  2. Symmetric: a == b implies b == a.
  3. Transitive: a == b and b == c imply a == c.

Floating-point numbers famously break reflexivity: Double.nan == Double.nan is false. A struct holding a Double still synthesizes Equatable, but a value containing nan will not equal itself. Avoid storing nan in values you compare or use as keys.

Equatable for classes

Classes never synthesize Equatable. You write == yourself, usually comparing the stored properties that matter. Mark the class final to keep the comparison simple; with inheritance, == is declared for the base class and subclasses must be handled with care. When identity is what you want, compare with === instead, as shown in Value vs. Reference Semantics.

Hashable: set members and dictionary keys

A hash is an integer summary of a value. Set and Dictionary use hashes to find elements in roughly constant time instead of scanning. A type must conform to Hashable to be an element of a Set or a key of a Dictionary. Hashable inherits from Equatable, so equal values must produce equal hashes.

Again, synthesis does the work if all stored properties are Hashable:

Swift A struct as dictionary key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Looking up Cell(row: 7, column: 4) finds king because a new Cell with the same fields is equal to the stored key. Inserting an equal cell a second time into a Set does nothing and reports inserted == false. This "grid coordinate as key" pattern is extremely common in puzzle and game code.

Writing hash(into:) by hand

If you wrote a custom ==, you must also write a matching hash(into:). The rule is one line long: if a == b, then a and b must feed the same data to the hasher. Feed the hasher exactly the properties that == looks at, no more.

Swift Custom hashing that matches ==

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The set treats repriced as a duplicate, so the count stays 1 and the original price (20.0) is kept. If hash(into:) also fed price into the hasher, equal products would hash differently and the set could contain "duplicates" or fail to find an element it holds. That is a silent, nasty bug.

Swift's hashing is randomly seeded for each process to resist denial-of-service attacks. Never print hashValue or rely on set or dictionary order. In the example we only compare two hashes within a single run. To get a stable order, sort the elements before printing.

Do not mutate what you hash

If an object is inside a Set or is a dictionary key and a property that takes part in hashing changes, the element is now filed under the wrong bucket and lookups fail. Structs sidestep this because you cannot mutate a key in place (a copy goes in). It is a real hazard with mutable classes, which is one more reason to prefer immutable properties on hashed types.

Comparable: ordering

Comparable adds <, <=, > and >= and enables sorted(), min(), max() and sort(). You implement a single method, <; the other three come for free.

Swift Making a type sortable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The versions come out in the order 1.9.4, 1.10.0, 2.0.0, 2.0.1, which a plain string sort would get wrong ("1.10.0" sorts before "1.9.4" as text). The newest is 2.0.1, and >= works for equal versions because Version also became Equatable through synthesis.

Comparable must be a strict weak ordering: it should never say both a < b and b < a, and elements that are neither less than nor greater than each other must be treated consistently as equal. If your < is inconsistent, sort may produce nonsense or even crash in the worst case.

Comparing several fields with a tuple

Writing nested if statements gets tedious. Tuples of Comparable values are themselves comparable, element by element, so you can compare tuples:

Swift Tuple comparison trick

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Swapping lhs and rhs on the score (and not the name) makes the score descending and the name ascending. The output is 90 Bo, 50 Abe, 50 Cleo. Note that the compiler cannot synthesize this particular ordering, so spelling out < is the right tool (the Equatable part is still synthesized).

Synthesized Comparable for enums

Enums without associated values can get Comparable for free: the cases are ordered by their declaration order.

Swift Comparable enums and sort descriptors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The sorted priorities print as ["low", "medium", "high"] (mapped to strings first, because printing the enum values directly inside an array adds the module name), and the chores are listed from high to low. You do not have to make a type Comparable just to sort it once: sorted(by:) with a closure is fine for ad-hoc ordering. Conform to Comparable when the ordering is the type's natural, single, obvious order.

Forgetting the conformance

If you use a type in a context that needs a protocol it does not have, the compiler tells you precisely what is missing.

Swift Missing Hashable (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The error reads main.swift:5:11: error: type 'Tag' does not conform to protocol 'Hashable'. Add : Hashable to Tag and it compiles, because String is already Hashable.

Quick reference

  • Equatable: gives == and !=. Synthesized when all stored properties are Equatable.
  • Hashable: gives hash(into:) and hashValue; required for Set elements and Dictionary keys. Synthesized when all properties are Hashable. Must agree with ==.
  • Comparable: gives <, <=, >, >=, sorted(), min(), max(). You write only <. Enums without payloads get it by declaring the conformance.
  • Conform in the declaration (or in an extension in the same file) so that synthesis can run.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does Swift synthesize == for a struct that declares Equatable?

    The compiler compares stored properties one by one, so it needs all of them to be Equatable.
  2. 2. You write a custom == that compares only id. What must hash(into:) do?

    Equal values must produce equal hashes. Feeding properties that == ignores would give equal values different hashes.
  3. 3. Which conformance does a type need to be a key in a Dictionary?

    Dictionary keys and Set elements must be Hashable, which also implies Equatable.
  4. 4. What do you have to implement to get <=, > and >= from Comparable?

    Comparable provides the other three operators in terms of <, so you write only static func <.
  5. 5. Why should you avoid printing hashValue or relying on the order of a Set?

    Swift randomizes hash seeds for security, so iteration order of sets and dictionaries differs between runs.

Summary

  • Equatable gives ==; Hashable gives set membership and dictionary keys; Comparable gives ordering and sorting.
  • Add the protocol to the declaration and let the compiler synthesize the code when all stored properties conform.
  • Write == by hand when only some properties define identity, and then write a matching hash(into:) that combines the same properties.
  • Custom == and < must obey the laws (reflexive, symmetric, transitive; strict weak ordering).
  • Compare tuples to order by several keys; use sorted(by:) for one-off orderings.
  • Never rely on hash values or on Set and Dictionary iteration order. Sort before printing.

Next: Codable