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 (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.
Rate your understanding: