These protocols help you compare and organize your data easily. They let you check if things are equal, use them in sets or dictionaries, and sort them.
Equatable, Hashable, Comparable protocols in Swift
struct MyType: Equatable, Hashable, Comparable { static func == (lhs: MyType, rhs: MyType) -> Bool { // return true if lhs and rhs are equal return true // placeholder implementation } func hash(into hasher: inout Hasher) { // combine properties to create a hash } static func < (lhs: MyType, rhs: MyType) -> Bool { // return true if lhs is less than rhs return false // placeholder implementation } }
Equatable requires you to define how to check if two values are equal.
Hashable requires you to provide a way to create a unique number (hash) for your object.
Comparable requires you to define how to compare two values to sort them.
struct Person: Equatable { var name: String var age: Int static func == (lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name && lhs.age == rhs.age } }
struct Person: Equatable, Hashable { var name: String var age: Int static func == (lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name && lhs.age == rhs.age } func hash(into hasher: inout Hasher) { hasher.combine(name) hasher.combine(age) } }
struct Person: Equatable, Comparable { var name: String var age: Int static func == (lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name && lhs.age == rhs.age } static func < (lhs: Person, rhs: Person) -> Bool { return lhs.age < rhs.age } }
This program defines a Person struct that can be compared, hashed, and checked for equality. It creates a list with duplicates, removes duplicates by converting to a Set, then sorts the unique people by age and prints their names and ages.
struct Person: Equatable, Hashable, Comparable { var name: String var age: Int static func == (lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name && lhs.age == rhs.age } func hash(into hasher: inout Hasher) { hasher.combine(name) hasher.combine(age) } static func < (lhs: Person, rhs: Person) -> Bool { return lhs.age < rhs.age } } var people: [Person] = [ Person(name: "Alice", age: 30), Person(name: "Bob", age: 25), Person(name: "Charlie", age: 30), Person(name: "Alice", age: 30) ] // Remove duplicates using a Set let uniquePeople = Set(people) // Sort unique people by age let sortedPeople = uniquePeople.sorted() for person in sortedPeople { print("\(person.name), \(person.age)") }
Swift can automatically generate Equatable and Hashable implementations for structs if all properties conform.
Comparable requires you to define the < operator to decide sorting order.
Hashable is important for using your objects in sets and as dictionary keys.
Equatable lets you check if two values are equal.
Hashable lets you use your objects in sets and dictionaries.
Comparable lets you sort your objects.