Post

Replies

Boosts

Views

Activity

Not append new data in an array
Hi I want to add new data to a list in my project but I can't do it I have a ContentView.swift view for showing products list and in another view (ShopView) I want to add data to products array My products array and my addProduct() function in the Products.swift file Please help me Thanks ContentView.swift struct ContentView: View {     @ObservedObject var cart = Products()     var body: some View {         NavigationView{             List {                 ForEach(cart.products) { product in                     Text("\(product.name) \(product.price)$")                 }             }             .navigationBarItems(                 trailing: NavigationLink(destination: Shop()) {                     Text("Go Shop")                 })             .navigationBarTitle("Cart")         }     } } Product.swift struct Product: Identifiable {     var id = UUID()     var name: String     var price: Int } Products.swift struct Shop: View {     @ObservedObject var cart = Products()     var body: some View {         VStack{             Button("Add Product To Cart") {                 cart.addProduct(product: Product(name: "Name", price: 399))             }         }     } } Products.swift class Products: ObservableObject {     @Published var products = [Product]()     func addProduct(product: Product) {         products.append(product)         print("Product Added")     } }
1
0
1.6k
May ’21