What if you could teach your app to instantly know when two things are the same or which one comes first, without writing extra code every time?
Why Equatable, Hashable, Comparable protocols in Swift? - Purpose & Use Cases
Imagine you have a list of friends and you want to find if a particular friend is already in your list, or you want to sort them by their names. Doing this by checking each friend manually one by one or writing custom code every time can be tiring and slow.
Manually comparing each friend's details every time you want to check equality or order is error-prone and repetitive. It's easy to forget a detail or write inconsistent code, which leads to bugs and wasted time.
Swift's Equatable, Hashable, and Comparable protocols let you define simple rules once, so the system can automatically check if two items are equal, store them efficiently in collections, or sort them. This saves time and avoids mistakes.
func areFriendsEqual(f1: Friend, f2: Friend) -> Bool {
return f1.name == f2.name && f1.age == f2.age
}struct Friend: Equatable, Hashable, Comparable {
let name: String
let age: Int
static func < (lhs: Friend, rhs: Friend) -> Bool {
return lhs.name < rhs.name
}
}It enables you to easily compare, store, and sort your data with simple, reusable rules that the system understands.
Think about a contacts app that needs to quickly find if a contact exists, sort contacts alphabetically, or store them in a phonebook without duplicates. These protocols make that smooth and reliable.
Manually comparing or sorting data is slow and error-prone.
Equatable, Hashable, Comparable let you define simple rules once.
These protocols help your app compare, store, and sort data easily and correctly.
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
