Browse Questions
- These protocols define how types support equality checks, hashing, and ordering.
- Most candidates fail coding interviews not because they can't code, but because they lack a structured thinking process.
- ARC is Swift's compile-time memory management system that automatically inserts retain and release calls to allocate and free class instances on the heap.
- These determine how ARC (Automatic Reference Counting) manages object lifetimes.
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 (requiresEquatable)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.