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.
Practice
Which protocol in Swift allows you to check if two instances of a type are equal using ==?
Solution
Step 1: Understand the purpose of Equatable
Equatable protocol allows comparing two instances for equality using==.Step 2: Compare with other protocols
Hashable is for hashing, Comparable is for ordering, Codable is for encoding/decoding.Final Answer:
Equatable -> Option DQuick Check:
Equality check = Equatable [OK]
- Confusing Hashable with Equatable
- Thinking Comparable checks equality
- Mixing Codable with Equatable
Which of the following is the correct way to declare a struct Person that conforms to Equatable and Hashable?
struct Person: ??? {
var name: String
var age: Int
}Solution
Step 1: Identify needed protocols
To compare equality and use in sets/dictionaries, use Equatable and Hashable.Step 2: Check syntax for protocol conformance
Protocols are listed separated by commas after colon in struct declaration.Final Answer:
Equatable, Hashable -> Option AQuick Check:
Equality + hashing = Equatable, Hashable [OK]
- Using Comparable instead of Equatable
- Forgetting commas between protocols
- Using Codable instead of Equatable
What will be the output of the following Swift code?
struct Item: Comparable {
var value: Int
static func < (lhs: Item, rhs: Item) -> Bool {
return lhs.value < rhs.value
}
}
let items = [Item(value: 3), Item(value: 1), Item(value: 2)]
let sortedValues = items.sorted().map { $0.value }
print(sortedValues)Solution
Step 1: Understand Comparable conformance
The<operator comparesvalueproperties to sort ascending.Step 2: Analyze sorting and mapping
Sorting the array orders items by value: 1, 2, 3. Mapping extracts values in this order.Final Answer:
[1, 2, 3] -> Option BQuick Check:
Sorted values ascending = [1, 2, 3] [OK]
- Assuming descending order by default
- Confusing map output with original array
- Forgetting to implement < operator
Identify the error in this Swift struct that tries to conform to Hashable:
struct Book: Hashable {
var title: String
var pages: Int
func hash(into hasher: inout Hasher) {
hasher.combine(title)
}
}Solution
Step 1: Check Hashable requirements
Hashable requires hashing all properties that affect equality.Step 2: Analyze hash(into:) implementation
Onlytitleis combined;pagesis missing, causing incorrect hashing.Final Answer:
Missing combine call for all properties in hash(into:) -> Option AQuick Check:
Hash all relevant properties [OK]
- Hashing only some properties
- Forgetting to implement == operator if needed
- Wrong method signature for hash(into:)
You want to create a struct Player that can be stored in a Set, compared for equality, and sorted by score descending. Which protocols should Player conform to, and how should you implement the sorting?
Solution
Step 1: Identify needed protocols
To store in Set and check equality, conform to Equatable and Hashable. To sort, conform to Comparable.Step 2: Implement sorting logic
Implement<operator to compare scores descending by reversing comparison.Final Answer:
Conform to Equatable, Hashable, Comparable; implement < for descending scores -> Option CQuick Check:
Set + equality + custom sort = Equatable, Hashable, Comparable [OK]
- Forgetting Comparable for sorting
- Sorting ascending instead of descending
- Missing Equatable or Hashable for Set storage
Ready to prove it?
Pass the test and this pattern moves unknown
