SwiftMidMCQ

What is `Hashable`, `Equatable`, and `Comparable`?

Test your knowledge:

Explanation & Code

Answer: These protocols define how types support equality checks, hashing, and ordering.

  • Equatable — can compare with ==
  • Hashable — can be used as dictionary keys or in sets (requires Equatable)
  • Comparable — can be ordered with <, >, etc.

Code Example:

struct Point: Hashable, Comparable {
    let x: Int
    let y: Int

    // Comparable — sort by x, then y
    static func < (lhs: Point, rhs: Point) -> Bool {
        lhs.x == rhs.x ? lhs.y < rhs.y : lhs.x < rhs.x
    }
}

let points: Set<Point> = [Point(x: 1, y: 2), Point(x: 3, y: 4)]
let sorted = points.sorted() // works because of Comparable

Note: Swift auto-synthesizes Equatable and Hashable for structs if all stored properties conform.

Rate your understanding:

Ready to practice more Swift?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.