SwiftUI ForEach of dictionary 确定的问题

SwiftUI ForEach of dictionary identified issue

使用下面的给定代码,我尝试遍历字典 wordList,但失败并出现问题 Instance method 'identified(by:)' requires that '(key: Int, value: [String : String])' conform to 'Hashable'

所以我的猜测是我必须以某种方式将协议 Hashable 应用到字典的 Int 或者可能有另一个解决方案涉及 .identified(by:)

非常感谢您的帮助!

struct ContentView: View {
    @State var wordOrder = ["DE", "EN"]

    let wordList: [Int: [String: String]] = [
        0: [
            "DE": "Hallo Welt",
            "EN": "hello world"
        ],
        1: [
            "DE": "Tschüss",
            "EN": "goodbye"
        ],
        2: [
            "DE": "vielleicht",
            "EN": "maybe"
        ]
    ]

    var body: some View {
        Group {
            NavigationView {
                List() {
                    ForEach(wordList.identified(by: \.self)) { wordListEntry in
                        let lang1 = wordListEntry[wordOrder[0]]
                        let lang2 = wordListEntry[wordOrder[1]]
                        WordRow(lang1, lang2)
                    }
                }
                .navigationBarTitle(Text("Alle Wörter"))
            }
        }
    }
}

看来你是误会了。根据您发布的代码,我猜您认为遍历字典就是遍历字典中的值。但这不是字典迭代的工作方式。

当您遍历字典时,您会收到 。每对包含一个键和字典中的相应值。在您的代码中,wordListEntry 的类型是 (key: Int, value: [String: String]),一对第一个元素是 Int 类型的 key,第二个元素是 value 类型 [String: String].

我想你只想遍历字典的键,然后在 ForEach 正文中查找相应的值,如下所示:

ForEach(wordList.keys.sorted().identified(by: \.self)) { key in
    let lang1 = wordListEntry[wordOrder[0]]
    let lang2 = wordListEntry[wordOrder[1]]
    return WordRow(lang1, lang2)
}

更新为最新 swift UI:

    ForEach(wordList.keys.sorted(), id: \.self) { key in
    let lang1 = wordListEntry[wordOrder[0]]
    let lang2 = wordListEntry[wordOrder[1]]
    return WordRow(lang1, lang2)
}