Hi Chris,
From your initial post, it looks like you want to create an app with a store sort of thing? If that's the case, I would recommend using EnvironmentObject for the number of pens etc. This is what I came up with:
class StationaryStore: ObservableObject {
@Published private(set) var total: Double = 0
@Published private(set) var pens: Double = 0
@Published private(set) var watches: Double = 0
@Published private(set) var markers: Double = 0
@Published private var penPrice: Double = 20
@Published private var watchPrice: Double = 200
@Published private var markerPrice: Double = 10
enum product {
case pen
case watch
case marker
}
func add(_ product: product, _ quantity: Double) {
switch product {
case .pen:
pens += quantity
total += penPrice
case .watch:
watches += quantity
total += watchPrice
case .marker:
markers += quantity
total += markerPrice
}
}
func remove(_ product: product, _ quantity: Double) {
switch product {
case .pen:
pens -= quantity
total -= penPrice
case .watch:
watches -= quantity
total -= watchPrice
case .marker:
markers -= quantity
total -= markerPrice
}
}
}
struct ContentView: View {
var store = StationaryStore()
var body: some View {
PurchaseView().environmentObject(store)
}
}
struct PurchaseView: View {
@EnvironmentObject var store: StationaryStore
var body: some View {
VStack {
Stepper("Pens", onIncrement: {
store.add(.pen, 1)
}, onDecrement: {
self.store.pens != 0 ? store.remove(.pen, 1) : nil
}).padding(10)
Stepper("Watches", onIncrement: {
store.add(.watch, 1)
}, onDecrement: {
self.store.watches != 0 ? store.remove(.watch, 1) : nil
}).padding(10)
Stepper("Pens", onIncrement: {
store.add(.marker, 1)
}, onDecrement: {
self.store.markers != 0 ? store.remove(.marker, 1) : nil
}).padding(10)
// For testing (instead of checkout View -
// don't have time to code it)
Text("Pens: \(self.store.pens)")
Text("Watches: \(self.store.watches)")
Text("Markers: \(self.store.markers)")
Text("Total: \(self.store.total)")
}
}
}
As you can see, in ContentView, a new instance of Store is created, then passed to each view you'd like (only PurchaseView at the moment) so it can be accessed. This means the store data you modify in purchase view can be easily accessed in your eventual CheckoutView. I also made the Store's variables private(set) meaning they are read-only outside of the class. The only thing that modifies those variables are the add() and remove() functions I added within that class. This will help prevent bugs :)
Any other questions, feel free to reply. I also welcome corrections or additions from other people!
Ed
p.s. There is probably a more efficient way of ensuring steppers with custom functionality don't go below zero... but this is just a base.