Browse Questions
  • SwiftUI compares the new view tree with the previous one on every state change.
  • These protocols define how types support equality checks, hashing, and ordering.
  • All three transform collections but handle the results differently.
  • To create a custom Xcode File Template from scratch, create a .xctemplate directory inside ~/Library/Developer/Xcode/Templates/File Templates/<Category>/, add a TemplateInfo.plist declaring the…

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.