SwiftUI iterating through dictionary with ForEach

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

Leave a Comment