Hi,
I’ve been stuck on how to get the correct display for the Pizza App for the last several challenges. I am not sure where I messed up. Any advice? I’m pasting my codes below.
Thanks in advance.
//
// Day_23_ChallengeApp.swift
// Day 23 Challenge
//
// Created by Ellie on 2/18/23.
//
import SwiftUI
@main
struct Day_23_ChallengeApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
//
// ContentView.swift
// Day 23 Challenge
//
// Created by Ellie on 2/18/23.
//
import SwiftUI
struct ContentView: View {
@ObservedObject var model = PizzaModel()
var body: some View {
ScrollView {
VStack(alignment: .leading) {
ForEach (model.pizzas) { pizza in
PizzaView(pizza: pizza)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
//
// PizzaView.swift
// Day 23 Challenge
//
// Created by Ellie on 2/21/23.
//
import SwiftUI
struct PizzaView: View {
var pizza:Pizza
var body: some View {
HStack {
Image(pizza.image)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 60, height: 60)
.cornerRadius(5)
.clipped()
VStack(alignment: .leading) {
Text(pizza.name)
.font(.headline)
HStack {
ForEach (pizza.toppings, id:\.self) { topping in
Text(topping)
}
}
.font(.caption)
}
}
}
}
struct PizzaView_Previews: PreviewProvider {
static var previews: some View {
PizzaView(pizza: Pizza(id: UUID(), name: "Test", toppings: ["topping1", "topping2"], image: "Meat Lovers"))
}
}
//
// PizzaModel.swift
// Day 23 Challenge
//
// Created by Ellie on 2/18/23.
//
import Foundation
class PizzaModel: ObservableObject {
@Published var pizzas = [Pizza]()
init() {
let pathString = Bundle.main.path(forResource: "pizzas", ofType: "json")
if pathString != nil {
let url = URL(fileURLWithPath: pathString!)
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
do {
var jsonPizzas = try decoder.decode([Pizza].self, from: data)
for index in 0..<jsonPizzas.count {
jsonPizzas[index].id = UUID()
}
self.pizzas = jsonPizzas
}
catch {
print("Couldn't parse Pizzas")
}
}
catch {
print("Couldn't create Data object")
}
}
}
}
//
// Pizza.swift
// Day 23 Challenge
//
// Created by Ellie on 2/18/23.
//
**import** Foundation
**struct** Pizza: Identifiable, Decodable {
**var** id:UUID?
**var** name:String
**var** toppings:[String]
**var** image:String
}
[
{ "name": "Meat Lovers",
"toppings": ["Pepperoni", "Bacon", "Sausage"],
"image":"Meat Lovers"
},
{ "name: "Hawaiian",
"toppings": ["Ham", "Bacon", "Pineapple"],
"image":"Hawaiian"
},
{ "name": "Deluxe",
"toppings": ["Pepperoni", "Green Peppers", "Mushroom"],
"image':"Deluxe"
}
]