当没有字典时,“在字典中发现...类型的重复键”?

ano*_*her 6 foundation swift

我对 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{}
Run Code Online (Sandbox Code Playgroud)

(我删除了func的内容,因为它对你没用)

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

let foundWords = solver.findValidWords()
    
for found in foundWords {
    wordList.append(ScoredWord(word: found))
}
Run Code Online (Sandbox Code Playgroud)

在我看来,该数组的使用方式如下:

 List(wordListViewModel.wordList, id: \.self) { // 1 Word list
     Text( $0.word )
     Spacer()
     Text("\( $0.points )")
 }
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

我发现这篇文章关于相同的错误,其中评论指出该错误将来自列表显示得不够快并且 id 混淆,但没有任何关于如何修复它的信息...

任何想法?

Clo*_*ing 8

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

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

  • 您是否更新了“==”函数(即 equatable 函数)以将 UUID 也考虑在内? (2认同)