SwiftUI: How do I access nested array data from a data model?

Viewed 28

I tried wrapping my head around it for 3 hours now (I'm not even exaggerating, it's sad I know), but I don't understand how I access my nested array in my data model.

DataModel (simplified)

struct PlantData: Decodable, Identifiable {
    var speciesKey: Int?
    var family: String?
    var species: String?
    var vernacularNames: [VernacularNames]?
    var id: Int { speciesKey ?? 0 }
}

struct VernacularNames: Decodable {
    var vernacularName: String?
    var language: String?
}

Section from ViewModel

@Published var plantData = [PlantData]()

View with a loop showing speciesKey, family and species perfectly fine.

struct PlantSelection: View {

@EnvironmentObject var model: DataModel

var body: some View {
    
    // List all plants
    ForEach(model.plantData) { plant in
        
        VStack {
                
            HStack {
               Text(plant.species ?? "")
               Spacer()
               Text(plant.vernacularNames?.vernacularName) // Error: Value of type '[VernacularNames]' has no member 'vernacularName'
               Text(plant.vernacularNames?.language) // Error: Value of type '[VernacularNames]' has no member 'language'
            }
                
            HStack {
               Text(plant.family ?? "")
               Spacer()
            }
                
        }
    }
        
    Divider()
    }
}

I don't understand why I am getting this error message. Clearly, I am doing something wrong here.

1 Answers

1 hour and helpful comments later, I have a working solution:

HStack {

    Text(plant.species ?? "")

    Spacer()

    if plant.vernacularNames != nil {
                        
        ForEach(plant.vernacularNames!, id: \.self) { item in
            if item.language == "xxx" {
                Text(item.vernacularName!)
            }
        }
     }
}

Big thanks to @vadian for pointing me in the right direction!

Related