Created
June 2, 2020 18:21
-
-
Save Exey/2dc0bdcc033add021ea9074e2b089180 to your computer and use it in GitHub Desktop.
Flux on Swift 5.3
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
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { | |
let store = Store<Int, CounterAction>(initialState: 0) { previousState, action in | |
switch action { | |
case .increment: | |
return previousState + 1 | |
case .decrement: | |
return previousState - 1 | |
} | |
} | |
let contentView = ContentView().environmentObject(store) | |
// Use a UIHostingController as window root view controller. | |
if let windowScene = scene as? UIWindowScene { | |
let window = UIWindow(windowScene: windowScene) | |
window.rootViewController = UIHostingController(rootView: contentView) | |
self.window = window | |
window.makeKeyAndVisible() | |
} | |
} | |
import SwiftUI | |
import Combine | |
final class Store<State, Action>: ObservableObject { | |
typealias Reducer = (State, Action) -> State | |
private let reducer: Reducer | |
@Published var state: State | |
init(initialState: State, reducer: @escaping Reducer) { | |
state = initialState | |
self.reducer = reducer | |
} | |
func dispatch(action: Action) { | |
state = reducer(state, action) | |
} | |
} | |
enum CounterAction { | |
case increment | |
case decrement | |
} | |
struct ContentView: View { | |
@EnvironmentObject var store: Store<Int, CounterAction> | |
var body: some View { | |
VStack { | |
VStack(spacing: 30) { | |
Text("\(store.state)") | |
.font(.largeTitle) | |
HStack { | |
Button { | |
store.dispatch(action: .increment) | |
} label: { | |
Text("Up") | |
} | |
Spacer() | |
Button { | |
store.dispatch(action: .decrement) | |
} label: { | |
Text("Down") | |
} | |
} | |
.frame(width: 180) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment