The Hashable
protocol in Swift enables a type to be converted into a unique integer value, allowing it to be used in hash-based collections like Set
and Dictionary
. This is especially useful for ensuring uniqueness and enabling fast lookups. By conforming to Hashable
, Swift can compute a hash value for each instance, making it efficient to store, compare, and retrieve values in hashed collections.
Why Hashable is important ?
If you want to use your custom type as a key in a Dictionary or add it to a Set, Swift must know:
- How to compare the instances (Equatable).
- How to hash them into an integer (Hashable).
struct User: Hashable {
var id: Int
var name: String
}
// Now you can do this:
let u1 = User(id: 1, name: "Ali")
let u2 = User(id: 2, name: "Sara")
let users: Set = [u1, u2] // OK ✅
let userMap: [User: String] = [u1: "Admin", u2: "Guest"] // OK ✅
If User didn’t conform to Hashable Protocol, this would throw a compile-time error.
let u1 = User(id: 1, name: "Ali")
let u2 = User(id: 1, name: "Ali")
Since the variables u1
and u2
have the same property values, they produce the same hash value. This is how Set
and Dictionary
maintain uniqueness.
🔍 Note:
Please remember, don’t confuse Hashable with Hashing itself. Hashing is the process of converting data into a hash value (usually an integer)
Conclusion
The Hashable
protocol is a fundamental building block for working with sets, dictionaries, and efficient collections in Swift. By understanding how it works, you’ll write cleaner, faster, and more maintainable code — especially when dealing with custom models in iOS development.
📚 Related Reading:
Hashing in iOS – Understand the basic concept