-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproduct.swift
68 lines (56 loc) · 1.82 KB
/
product.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import SwiftUI
struct ProductView: View {
@StateObject var viewModel = ViewModel()
let availableProducts = [
Product(name: "Jacket", price: 124.99),
Product(name: "Jeans", price: 69.99),
Product(name: "Hat", price: 15.99)
]
var body: some View {
VStack {
Form {
Section("Add") {
ForEach(availableProducts, id: \.id) { product in
Button {
viewModel.addProduct(product)
} label: {
Text("Add \(product.name)")
}
}
}
Section("Delete") {
ForEach(availableProducts, id: \.id) { product in
Button {
viewModel.deleteProduct(product)
} label: {
Text("Delete \(product.name)")
}
}
}
Section("In Cart") {
ForEach(viewModel.products, id: \.id) { product in
Text(product.name)
}
}
}
Text("Total: \(viewModel.total)")
}
}
}
final class ViewModel: ObservableObject {
@Published private(set) var products: [Product] = []
@Published private(set) var total = 0.0
func addProduct(_ product: Product) {
products.append(product)
total += product.price
}
func deleteProduct(_ product: Product) {
products = products.filter { product.id != $0.id }
total -= product.price
}
}
struct Product {
let id = UUID()
let name: String
let price: Double
}