'" Duplicate keys of type ... were found in a Dictionary " when there is no Dictionary?
I'm quite new to Swift and I just encountered an error I don't find a solution for. I'm currently working on a game (Boggle, for the curious) and I want to update the list of words that the algorithm has found.
I created a struct to hold each word and the points it scores :
struct ScoredWord: Comparable, Identifiable{
let word: String
var points: Int = 0
let id: UUID
init(word: String){
self.id = UUID()
self.word = word
self.points = self.defineScore(word: word)
}
static func < (lhs: ScoredWord, rhs: ScoredWord) -> Bool {}
static func == (lhs: ScoredWord, rhs: ScoredWord) -> Bool {}
func hash(into hasher: inout Hasher) {
private func defineScore(word: String) -> Int{}
(I removed the content of the func for it's useless to you)
Once the algorithm is done, I have simple loop that created a struct for each word found and stores it in the array that is @Published for display
let foundWords = solver.findValidWords()
for found in foundWords {
wordList.append(ScoredWord(word: found))
}
The array is used in my view this way:
List(wordListViewModel.wordList, id: \.self) { // 1 Word list
Text( $0.word )
Spacer()
Text("\( $0.points )")
}
The error I get when I run all of this is:
Fatal error: Duplicate keys of type 'ScoredWord' were found in a Dictionary.
This usually means either that the type violates Hashable's requirements, or
that members of such a dictionary were mutated after insertion.
I found this post about the same error where a comment states that the error would come from the list not being displayed fast enough and id getting mixed up, but nothing about how to fix it...
Any idea?
Solution 1:[1]
I think you are missing a full conformance to the Hashable Protocol
Pay attention to the func hash(into hasher: inout Hasher)
function which you are missing
Solution 2:[2]
Hash table is a dictionary. What is the true difference between a dictionary and a hash table?
It appears that some structs in your array are made using identical words & points. Add another variable to your struct:
var identifier = UUID()
It will generate a unique ID.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | cora |