Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI conforming to Hashable

Tags:

swiftui

How can we make a SwiftUI object, Image, in particular, conform to Hashable protocol?

I know they conform to the Equatable protocol, so the main question would be how to get a Hash value, or use the hash(into:) function?

like image 305
Hamoonist Avatar asked Nov 06 '22 11:11

Hamoonist


1 Answers

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.

Source: https://www.hackingwithswift.com/example-code/language/how-to-conform-to-the-hashable-protocol

This may also be of help as well.

like image 84
fulvio Avatar answered Nov 23 '22 03:11

fulvio