Posted in

Hashable Protocol in iOS Swift Understand the basic concept

Hashable ios

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:

  1. How to compare the instances (Equatable).
  2. 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

I'm a passionate iOS Developer with over 10 years of experience building high-quality iOS apps using Objective-C, Swift, and SwiftUI. I created iostutor.com to share practical tips, tutorials, and insights for developers of all levels.

When I’m not coding, I enjoy exploring new technologies and writing content — from technical guides to stories and poems — with the hope that it might help or inspire someone, somewhere.

Leave a Reply

Your email address will not be published. Required fields are marked *