Array of dictionaries to list view SwiftUI

Viewed 4402

I have an array of dictionaries I would like to populate in a list view with SwiftUI.

I used for loops in the past but since that's not possible within a View I'm stuck as to what to do. I'm able to achieve partial results with the code below.

struct Test : View {
let dict = csvArray[0]

var body: some View {
    let keys = dict.map{$0.key}
    let values = dict.map {$0.value}

    return List {

        ForEach(keys.indices) {index in
            HStack {
                Text(keys[index])
                Text("\(values[index])")
            }
        }
    }
}
}

I'm looking to index through the entire Array of dictionaries and append them to the list, not just csvArray[0].

1 Answers

This is like Sections of key values, right?

So do it like:

This is an example of csvArray, This could be anything but you should update the rest of the code duo to the original data type

let csvArray = [
    [ "section0-key0": "section0-value0",
      "section0-key1": "section0-value1"],

    [ "section1-key0": "section1-value0",
      "section1-key1": "section1-value1"],

    [ "section2-key0": "section2-value0",
      "section2-key1": "section2-value1"]
]

This is your code for a single dictionary. but this will take that dictionary instead of hardcoded one:

struct SectionView : View {
    @State var dict = [String: String]()

    var body: some View {
        let keys = dict.map{$0.key}
        let values = dict.map {$0.value}

        return  ForEach(keys.indices) {index in
            HStack {
                Text(keys[index])
                Text("\(values[index])")
            }
        }
    }
}

And this is the list builder connected to the original array. I used sections for the meaningfulness of the data structure.

struct ContentView: View {
    var body: some View {
        List {
            ForEach(csvArray, id:\.self) { dict in
                Section {
                    SectionView(dict: dict)
                }
            }
        }
    }
}

Note that you can't relay on the order of the key value in a dictionary. So I suggest you to do some sorting before populating the list or use another data structure like class or struct instead of a plain dictionary.

Related