struct Point: Equatable { var x: Int var y: Int } let p1 = Point(x: 3, y: 4) let p2 = Point(x: 3, y: 4) print(p1 == p2)
The struct Point conforms to Equatable. Since both x and y are Int (which is Equatable), Swift automatically synthesizes the == operator. The two points have the same values, so p1 == p2 is true.
struct User: Hashable { var id: Int var name: String } let user1 = User(id: 1, name: "Alice") let user2 = User(id: 1, name: "Alice") print(user1.hashValue == user2.hashValue)
The User struct conforms to Hashable. Swift automatically generates hashValue based on all properties. Since user1 and user2 have identical id and name, their hash values are equal, so it prints true.
struct Box: Comparable { var volume: Int static func < (lhs: Box, rhs: Box) -> Bool { return lhs.volume > rhs.volume } } let b1 = Box(volume: 10) let b2 = Box(volume: 20) print(b1 < b2)
The < operator is implemented to return lhs.volume > rhs.volume, which reverses the usual order. Since b1.volume is 10 and b2.volume is 20, b1 < b2 calls 10 > 20 which is false.
struct Person: Comparable { var age: Int static func < (lhs: Person, rhs: Person) -> Bool { return lhs.age < rhs.age } } let people = [Person(age: 30), Person(age: 20), Person(age: 40)] let sortedAges = people.sorted().map { $0.age } print(sortedAges)
The Person struct conforms to Comparable with < comparing age. The sorted() method sorts ascending by age. So the ages in order are [20, 30, 40].
Equatable and Hashable protocols consistently for a Swift type used as a dictionary key?Dictionaries use hash values to quickly find the bucket where a key might be stored. Then they use equality checks to confirm the exact key. If Equatable and Hashable are not consistent, dictionary lookups can fail or behave incorrectly. So both protocols must be implemented correctly and consistently.