I am following this video (it's Swift UI but i don't think that matters?): https://developer.apple.com/videos/play/wwdc2020/10119/
What i would like to have is a list of ingredients in SandwichDetail.swift
How do i do that? I tried this without luck:
2. Right now in my data there's only 1 ingredient and 1 amount per sandwich. What is the correct syntax for adding more ingredients to the testData in Sandwich.swift? Simply separating by comma after "]" gives me an error :/
My code:
What i would like to have is a list of ingredients in SandwichDetail.swift
How do i do that? I tried this without luck:
Code Block List { ForEach(ingredients) { ingredient Text(ingredient.name) } }
2. Right now in my data there's only 1 ingredient and 1 amount per sandwich. What is the correct syntax for adding more ingredients to the testData in Sandwich.swift? Simply separating by comma after "]" gives me an error :/
My code:
Code Block // // Sandwich.swift // import Foundation struct Ingredient: Identifiable { var id = UUID() var name: String var amount: String } struct Sandwich: Identifiable { var id = UUID() var name: String var ingredientCount: Int var isSpicy: Bool = false var ingredients: [Ingredient] } let testData = [ Sandwich(name: "Club", ingredientCount: 4, isSpicy: false, ingredients: [Ingredient(name:"Avocado", amount: "1")]), Sandwich(name: "Pastrami on rye", ingredientCount: 4, isSpicy: false, ingredients: [Ingredient(name:"Avocado", amount: "1")]), Sandwich(name: "French dip", ingredientCount: 4, isSpicy: false, ingredients: [Ingredient(name:"Avocado", amount: "1")]), Sandwich(name: "Banh mi", ingredientCount: 4, isSpicy: false, ingredients: [Ingredient(name:"Avocado", amount: "1")]), ]
Code Block // // ContentView.swift import SwiftUI struct ContentView: View { var sandwiches: [Sandwich] = [] var body: some View { NavigationView { List { ForEach(sandwiches) { sandwich in SandwichCell(sandwich: sandwich) } HStack { Spacer() Text("\(sandwiches.count) Sandwiches") .foregroundColor(.secondary) Spacer() } } .navigationBarTitle("Sandwiches") } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView(sandwiches: testData) } } struct SandwichCell: View { var sandwich: Sandwich var body: some View { NavigationLink(destination: Text(sandwich.name)) { VStack(alignment: .leading) { Text(sandwich.name) Text("\(sandwich.ingredientCount) ingredients") .font(.subheadline) .foregroundColor(.secondary) } } } }
Code Block // // SandwichDetail.swift import SwiftUI struct SandwichDetail: View { var sandwich: Sandwich var body: some View { Text(sandwich.name) } } struct SandwichDetail_Previews: PreviewProvider { static var previews: some View { SandwichDetail(sandwich: testData[0]) } }