【问题标题】:" Duplicate keys of type ... were found in a Dictionary " when there is no Dictionary?当没有字典时,“在字典中找到类型的重复键...”?
【发布时间】:2021-04-04 14:10:09
【问题描述】:

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

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

算法完成后,我有一个简单的循环,它为找到的每个单词创建一个结构并将其存储在 @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.

我发现this post 发现了同样的错误,其中一条评论指出该错误来自列表显示速度不够快并且 id 混淆了,但没有关于如何修复它...

有什么想法吗?

【问题讨论】:

  • hash(into:)中显示代码。

标签: swift foundation


【解决方案1】:

哈希表是一个字典。 What is the true difference between a dictionary and a hash table?

您的数组中的某些结构似乎是使用相同的单词和点组成的。将另一个变量添加到您的结构中:

var 标识符 = UUID()

它将生成一个唯一的 ID。

【讨论】:

  • 感谢您的帖子!我有同样的想法,并试图在过去为每个结构添加一个 ID,但它最终以同样的方式结束......我再次尝试使用 UUID,但我仍然得到我的错误
  • 如果不是这个,那么您应该查看错误消息的第二部分,其中提到了错误的协议一致性或属性突变
  • 只是为了它,将这些变量更改为让
  • 是的,这就是 CloudBalancing 在他的回答中所建议的
  • @ano0ther 只要确保同一个结构没有被多次使用。
【解决方案2】:

我认为您没有完全遵守Hashable Protocol

注意你缺少的func hash(into hasher: inout Hasher)函数

【讨论】:

  • 嗨@CloudBalancing,感谢您的回复,我确实错过了我的结构中的这个函数。添加它并没有解决我的问题:(
  • 请分享函数的实现,这可能意味着您的实现为两个不同的结构实例生成相同的哈希
  • 这是我所做的:func hash(into hasher: inout Hasher) { hasher.combine(id) hasher.combine(word) hasher.combine(points) }
  • 您是否更新了您的== 函数,即平等函数以将 UUID 也考虑在内?
  • 好吧,我真为自己感到羞耻。毕竟我应该添加 funcs 内容,你会更早发现这个错误......非常感谢@CloudBalancing,它解决了我的问题!
猜你喜欢
  • 2014-01-13
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 2015-03-01
  • 2019-04-18
  • 1970-01-01
相关资源
最近更新 更多