0

I am trying to display values from a nested array / struct. Here is my struct definition:

import Foundation

// MARK: - Station
struct Station:Codable, Identifiable  {
    let id, latitude, longitude, cp: String
    let pop, adresse, ville: String
    let prix: [Prix]
    
    // MARK: - Prix
    struct Prix: Codable, Identifiable{
        let nom, id, maj, valeur: String
        
    }
}

Here is my code just to prove that the data is there and it works correctly.

List {
                    
                    VStack(alignment: .leading) {
                        
                            ForEach (data) { item in
                            Text("id: \(item.id)")
                            Text("lon: \(item.longitude)")
                            Text("lat: \(item.latitude)")
                            
                            Text("\(item.prix[0].nom): \(item.prix[0].valeur)")
                            Text("\(item.prix[1].nom): \(item.prix[1].valeur)")
                            Text("\(item.prix[2].nom): \(item.prix[2].valeur)")
                            Text("\(item.prix[3].nom): \(item.prix[3].valeur)")
                        }
                    }
                }
 

I would like to use ForEach to display the data in the [Prix] array, because the number of items is variable.

I have tried lots of combinations of ForEach with an Id, and without but can't get this to work.

Thankyou

1
  • Have you tried a second ForEach for Prix? Commented Dec 13, 2021 at 17:37

1 Answer 1

1

Try using a nested ForEach.

For each Station in data, there is an array of Prix. You should use ForEach to iterate over item.prix so that you don't have an index out of range exception (it will create views for each Prix in item.prix)

List {
                    
//VStack(alignment: .leading) {                    
    ForEach (data) { item in
             Text("id: \(item.id)")
             Text("lon: \(item.longitude)")
             Text("lat: \(item.latitude)")
             ForEach (item.prix) { prix in 
                 Text("\(prix.nom): \(prix.valeur)")
             }
    }
//}
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.