Learn Courses My Dashboard

L12-Challenge Parsing JSON

This is my JSON file
[{
“pizzaName”: “Hawain”,
“toppings”: [“Cheese”,“Ham”,“tomato”]
},
{
“pizzaName”: “Sea food”,
“toppings”: [“Cheese”,“Fish”,“Clams”]
},
{
“pizzaName”: “Meat Lover”,
“toppings”: [“Cheese”,“Meat”,“Mutton”]
}
]

This is my Model

class Pizza: Decodable, Identifiable{

var id:UUID?

var pizzaName:String

var toppings:[String]

}

This is View.

@ObservedObject var model = PizzaModel()

var body: some View {
    
    VStack {
        List(model.pizzas) {p in
            VStack(alignment: .leading){
                Text(p.pizzaName)
                HStack() {
                    Text(p.toppings[0])
                    Text(p.toppings[1])
                    Text(p.toppings[2])
                }

My question is on displaying the pizza toppings. How do I display the toppings array dynamically Instead of using 0,1,2 to display as above

You need to do this:

var body: some View {
    VStack {
        List(model.pizzas) { pizza in
            VStack {
                Text(pizza.pizzaName)
                HStack {
                    ForEach(pizza.toppings, id: \.self) { topping in
                        Text(topping)
                    }
                }
            }

        }
    }
}