I have an array of types that conform to Hashable
these can be any type that conforms to hashable. The issue I'm having is that say I have an array of strings
let people = ["Joe", "Tom", "Bob", "Joe"]
if people[3] == people[people.firstIndex(of: "Joe")!] {
print(true) // Always true.
}
Hashable
has hashValue
which should be able to make these values unique, however, hashValue
matches for values that are the same. Is there a way that I can extend Hashable
so that every element conforming to it will get a UUID()
assigned and therefore not identical to any others?
Basically, is there a way to get id: UUID
on everything that conforms to Hashable
CodePudding user response:
You probably want to do this a slightly different way. Could your array be of Identifiable
instead? Then your example could be:
struct Person: Identifiable, Hashable {
let id = UUID()
let name: String
}
And each instance of Person
will have a unique hashValue:
let people = [Person(name: "Joe"), Person(name: "Joe"), Person(name: "Joe")]
people.map(\.hashValue) // e.g. -> [7672515142881976808, -2470749298227582550, 3252810522385000211]