Hi, the challenge sounds simple but I do not know how to parse an array, error seem to prompt that the issue is how data represented this is my Json, thank you!
[
{
“name”:”Margarita ”,
“toppings”: [“Mozarella”, “Tomato Sause“, “Olives”]
},
{
“name”:”Marinara”,
“toppings”: [“Tuna”, “Ansjovis”, “Squid”]
},
{
“name”:”Florentina”,
“toppings”: [“Egg”, “Mushrooms”, “Cheese”]
}
]
this is my model:
//
// PizzaMenu.swift
// pizzaMenu
//
// Created by Ewa Boer on 01/05/2021.
//
import Foundation
class PizzaMenu: Identifiable, Decodable {
var id:UUID?
var name = ""
var toppings = [String]()
}
and this is my MenuModel
//
// MenuModel.swift
// pizzaMenu
//
// Created by Ewa Boer on 01/05/2021.
//
import Foundation
class MenuModel: ObservableObject {
@Published var menu = [PizzaMenu]()
init() {
let pathString = Bundle.main.path(forResource: "data", ofType: "json")
if let path = pathString {
let url = URL(fileURLWithPath: path)
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
do {
let menuData = try decoder.decode([PizzaMenu].self, from: data)
for r in menuData {
r.id = UUID()
}
self.menu = menuData
}
catch {
print(error)
}
}
catch {
print(error)
}
}
}
}
and this is my view:
//
// ContentView.swift
// pizzaMenu
//
// Created by Ewa Boer on 01/05/2021.
//
import SwiftUI
struct ContentView: View {
@ObservedObject var model = MenuModel()
var body: some View {
VStack{
List(model.menu) {
r in
VStack {
Text(r.name)
Text(r.toppings)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}