SwiftUI iterating through dictionary with ForEach

后端 未结 7 1875

Is there a way to iterate through a Dictionary in a ForEach loop? Xcode says

Generic struct \'ForEach\' requires that \'[Str

7条回答
  •  囚心锁ツ
    2020-12-03 14:06

    You can sort your dictionary to get (key, value) tuple array and then use it.

    struct ContentView: View {
        let dict = ["key1": "value1", "key2": "value2"]
        
        var body: some View {
            List {
                ForEach(dict.sorted(by: >), id: \.key) { key, value in
                    Section(header: Text(key)) {
                        Text(value)
                    }
                }
            }
        }
    }
    

提交回复
热议问题