Skip to content

Instantly share code, notes, and snippets.

@tal
Last active June 29, 2016 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tal/42d5e6c7be653bc1343d1ddb97403f63 to your computer and use it in GitHub Desktop.
Save tal/42d5e6c7be653bc1343d1ddb97403f63 to your computer and use it in GitHub Desktop.
Redux swift example
import Foundation
struct DashResponse {}
enum AppActions {
case dashAction(DashActions)
case envAction(EnvActions)
}
enum DashActions {
case fetchingDash(fetchedAt: Date)
case fetchedDash(receivedAt: Date, payload: DashResponse)
}
enum EnvActions {
case login(userId: String)
}
func dashReducer(state: AppState.DashState, action: DashActions) -> AppState.DashState {
var dashState = state
switch action {
case .fetchingDash(let fetchedAt):
dashState.isFetching = true
dashState.fetchedAt = fetchedAt
case .fetchedDash(let receivedAt, let payload):
dashState.isFetching = false
dashState.receivedAt = receivedAt
dashState.contents = payload
}
return dashState
}
func envReducer(state: AppState.Env, action: EnvActions) -> AppState.Env {
var state = state
switch action {
case .login(let userId):
state = AppState.Env(currentUserId: userId)
}
return state
}
func appReducer(state: AppState = AppState(), action: AppActions) -> AppState {
var state = state
switch action {
case .dashAction(let dashAction):
state.dashState = dashReducer(state: state.dashState, action: dashAction)
case .envAction(let envAction):
state.env = envReducer(state: state.env, action: envAction)
}
return state
}
extension Date {
static var now: Date {
return Date(timeIntervalSinceNow: 0)
}
}
let action: AppActions = .dashAction(.fetchingDash(fetchedAt: .now))
let oldState = AppState()
let newState = appReducer(state: oldState, action: action)
struct AppState {
struct DashState {
var isFetching: Bool
var fetchedAt: Date?
var receivedAt: Date?
var contents: DashResponse?
}
struct Env {
let currentUserId: String
}
var dashState = DashState(isFetching: false, fetchedAt: nil, receivedAt: nil, contents: nil)
var env = Env(currentUserId: "asdf1234567890")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment