Our take on a Redux-inspired state management for Swift.
In your Package.swift
add the following:
dependencies: [
.package(url: "https://github.com/YodelTalk/Recombine.git", .branch("main"))
]
import Recombine
struct State: Changeable {
var counter = 0
}
enum Action {
case increase
case decrease
}
typealias AppStore = Store<Action, State>
func counterReducer(action: Action, state: State) -> State {
switch action {
case .increase:
return state.changed(\.counter, to: state.counter + 1)
case .decrease:
return state.changed(\.counter, to: state.counter - 1)
}
}
let logger = { (dispatch: @escaping AppStore.Dispatch, store: AppStore) in
return { (action: Action) in
print("Handling action: \(action)")
dispatch(action)
print("New state: \(store.counter)")
}
}
let store = AppStore(
initialState: State(),
reducers: [counterReducer],
middlewares: [logger]
)
store.dispatch(.increase)
store.dispatch(.decrease)
store.dispatch(.decrease)
store.counter // -1