没有字典的时候" Duplicate keys of type ... were found in a Dictionary "?



我对Swift很陌生,刚刚遇到一个错误,我找不到解决方案。我目前正在开发一款游戏(Boggle,好奇的人(,我想更新算法找到的单词列表。

我创建了一个结构来保存每个单词及其得分:

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{}

(我删除了函数的内容,因为它对你没有用(

算法完成后,我有一个简单的循环,为找到的每个单词创建一个结构,并将其存储在@Published的数组中以显示

let foundWords = solver.findValidWords()

for found in foundWords {
wordList.append(ScoredWord(word: found))
}

在我看来,数组是这样使用的:

List(wordListViewModel.wordList, id: .self) { // 1 Word list
Text( $0.word )
Spacer()
Text("( $0.points )")
}

当我运行所有这些时,我得到的错误是:

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.

我发现这篇关于同一错误的帖子,其中一条评论指出,错误将来自列表显示得不够快和id混淆,但没有说明如何修复它…

知道吗?

我认为您缺少了对哈希协议的完全一致性

注意您缺少的func hash(into hasher: inout Hasher)功能

哈希表是一个字典。字典和哈希表的真正区别是什么?

数组中的一些结构似乎是使用相同的单词&点。在结构中添加另一个变量:

var标识符=UUID((

它将生成一个唯一的ID。

最新更新