Skip to content

Instantly share code, notes, and snippets.

@hmlongco
Created July 14, 2023 00:24
Show Gist options
  • Save hmlongco/473a5e2e990485aea1f776172071f7d7 to your computer and use it in GitHub Desktop.
Save hmlongco/473a5e2e990485aea1f776172071f7d7 to your computer and use it in GitHub Desktop.
ShopViewModel.swift
// Classic
class ShopViewModel: ObservableObject {
@Published private(set) var products: [Products]
init(products: [Products] = []) {
self.products = products
}
public func add(product) {
products.append(product)
}
public func remove(product) {
products.removeAll { $0 == product }
}
}
// State / Reducer
struct ShopState: Equatable {
var products: [String] = []
}
enum ShopAction: Equatable {
case add(String)
case remove(String)
}
let reduce: (ShopState, ShopAction) -> ShopState = { state, action in
var newState = state
switch action {
case let .add(product):
newState.products.append(product)
case let .remove(product):
newState.products.removeAll { $0 == product }
}
return newState
}
typealias ShopStore = Store<ShopState, ShopAction>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment