Created
September 28, 2022 19:34
-
-
Save damodarnamala/9740aed407cc7a11b655b73c1f95c1f7 to your computer and use it in GitHub Desktop.
Composable Swift example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ContentView.swift | |
// ReduxApp | |
// | |
// Created by Damodar Namala on 28/09/22. | |
// | |
import SwiftUI | |
import Combine | |
@main | |
struct ReduxAppApp: App { | |
var body: some Scene { | |
WindowGroup { | |
ContentView(store: store) | |
} | |
} | |
} | |
struct ContentView: View { | |
@ObservedObject var store: AppStore | |
init(store: AppStore) { | |
self.store = store | |
} | |
var body: some View { | |
VStack { | |
Image(systemName: "globe") | |
.imageScale(.large) | |
.foregroundColor(.accentColor) | |
Text(store.state.name) | |
Button { | |
self.store.action(.setName("Damodar")) | |
} label: { | |
Text("Fetch") | |
} | |
} | |
} | |
private func fetch() { | |
store.action(.setName("damodar")) | |
} | |
} | |
typealias Reducer<State, Action> = (State, Action) -> State | |
enum AppAction { | |
case setName(_ name: String) | |
} | |
struct AppState { | |
var name = "" | |
} | |
final class Store<State, Action>: ObservableObject { | |
@Published private(set) var state: State | |
private let reducer: Reducer<State, Action> | |
init(initialState: State, | |
reducer: @escaping Reducer<State, Action>) { | |
self.state = initialState | |
self.reducer = reducer | |
} | |
func action(_ action: Action) { | |
self.state = reducer(self.state, action) | |
} | |
} | |
let reducer: Reducer<AppState, AppAction> = { state, action in | |
var inState = state | |
if case let .setName(name) = action { | |
inState.name = name | |
} | |
return inState | |
} | |
typealias AppStore = Store<AppState, AppAction> | |
var store = AppStore(initialState: .init(), reducer: reducer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment