Learn Courses My Dashboard

Iterate over data struct

Hi all,
I’m new here and this is my first question, so please be kind.

I parse a json file onto a data structure that looks simplified as followed:

struct layer1: Codable {
      var layer2: newLayer
}
struct newLayer: Codable {
      var key1: Int
      var key2: Int
      ...
}

This works just fine and I can access each value with e.g.
layer1.layer2.key1

Now I want to make a list view of layer2 by iterating over it:

List {
      Section("Headline") {ForEach(layer1.layer2, id: \.self) {key in SelectionCell(bsp: key, 
       selectedItem: self.$selectedItem)}}
}

with SelectionCell as followed:

struct SelectionCell: View {
      let bsp: String
      @Binding var selectedItem: String?
      var body: some View {
            HStack {
                  Text(bsp)
                  Spacer()
                  Text(*value of the key*)
            }
     } 

I guess there are several problems in there:
layer1.layer2 is no “RandomAccessCollection” How can I make it one or is there a workaround? Other method of iteration for example?
can layer1.layer2 be used as a dictionary? It looks like one. That’s why I called the variable names key and their stored data value. How can I transform it to a dictionary or how can I implement the data structure for parsing that it is a dictionary from the beginning? I guess iterating over it would then be easier.

I`m just a beginner, so every help is appreciated.
Thanks
Frank

Hey Frank this is a very welcoming community and beginners are always welcome!!

To iterate through anything you need an array of some sort, is layer2 going to be an array of newLayer objects?

Also I would highly recommend as a good coding practice you capitalize the names of your structs

Thanks for the welcome!
Sorry, it was just an example, I will capitalize the names of my structs.

As I see it layer2 is at the moment just a struct with a bunch of variables in it. I could either make it to an array at the moment of parsing my json, but then I don’t know how I decode a very nested json to a struct with parts of it an array or dictionary. I only found examples online with parsing a complete json to a dictionary with JSONSerialization.jsonObject, but I don’t know how that would work in my case.

Ok, I have a solution that works for me.

Didn’t know that this was possible, but I just parse my json to a dictionary:

struct Layer1: Codable {
      var Layer2: Dictionary<String, Int>

Then I can iterate over it with:

List {
      Section("Headline") {ForEach(Array(Layer1.Layer2.keys).sorted(), id: \.self) {key in SelectionCell(bsp: key, 
       selectedItem: self.$selectedItem)}}
}