Swift version: 5.6
In Swift, conforming to the Hashable
protocol is often just as easy as adding Hashable
to your conformance list. However, if you have custom requirements, or use properties that don’t all conform to Hashable
, it takes a little more work.
Here’s an example struct we can work with:
struct iPad: Hashable {
var serialNumber: String
var capacity: Int
}
Because that conforms to the Hashable
protocol and both its properties also conform to the Hashable
protocol, Swift will generate a hash(into:)
method automatically.
However, in this case we can see that serialNumber
is enough to identify each iPad uniquely so hashing capacity
isn’t needed. So, we can write our own implementation of hash(into:)
that hashes just that one property:
func hash(into hasher: inout Hasher) {
hasher.combine(serialNumber)
}
You can add more properties to your hash by calling combine()
repeatedly, and the order in which you add properties affects the finished hash value.
Swift uses a random seed every time it hashes an object, which means the hash value for any object is effectively guaranteed to be different between runs of your app.
This in turn means that elements you add to a set or a dictionary are highly likely to have a different order each time you run your app.
SPONSORED AppSweep by Guardsquare helps developers automate the mobile app security testing process with fast, free scans. By using AppSweep’s actionable recommendations, developers can improve the security posture of their apps in accordance with security standards like OWASP.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 8.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.