Skip to content

Instantly share code, notes, and snippets.

@NicholasTD07
Last active October 5, 2016 10:21

Revisions

  1. Nicholas T revised this gist Oct 5, 2016. 1 changed file with 9 additions and 9 deletions.
    18 changes: 9 additions & 9 deletions redux.swift
    Original file line number Diff line number Diff line change
    @@ -1,32 +1,32 @@
    // Swift 2
    // Swift 3

    protocol ActionType { }

    struct InitialAction: ActionType { }

    class Store<State> {
    var state: State!
    typealias Reducer = (state: State?, action: ActionType) -> State
    typealias Reducer = (State?, ActionType) -> State
    final let reducer: Reducer

    init(with reducer: Reducer) {
    init(with reducer: @escaping Reducer) {
    self.reducer = reducer

    dispatch(InitialAction())
    }

    typealias Subscriber = (store: Store) -> ()
    typealias Subscriber = (Store) -> ()
    final var subscribers = [Subscriber]()

    final func dispatch(action: ActionType) {
    self.state = reducer(state: state, action: action)
    final func dispatch(_ action: ActionType) {
    self.state = reducer(state, action)
    subscribers.forEach {
    $0(store: self)
    $0(self)
    }
    }

    final func subscribe(with subscriber: Subscriber) {
    final func subscribe(with subscriber: @escaping Subscriber) {
    subscribers.append(subscriber)
    subscriber(store: self)
    subscriber(self)
    }
    }
  2. Nicholas T created this gist Oct 5, 2016.
    32 changes: 32 additions & 0 deletions redux.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    // Swift 2

    protocol ActionType { }

    struct InitialAction: ActionType { }

    class Store<State> {
    var state: State!
    typealias Reducer = (state: State?, action: ActionType) -> State
    final let reducer: Reducer

    init(with reducer: Reducer) {
    self.reducer = reducer

    dispatch(InitialAction())
    }

    typealias Subscriber = (store: Store) -> ()
    final var subscribers = [Subscriber]()

    final func dispatch(action: ActionType) {
    self.state = reducer(state: state, action: action)
    subscribers.forEach {
    $0(store: self)
    }
    }

    final func subscribe(with subscriber: Subscriber) {
    subscribers.append(subscriber)
    subscriber(store: self)
    }
    }