Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Last active May 17, 2021 20:48
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 gordonbrander/f4b689a82cc841ffb404885000e073b9 to your computer and use it in GitHub Desktop.
Save gordonbrander/f4b689a82cc841ffb404885000e073b9 to your computer and use it in GitHub Desktop.
SwiftUI immutable ViewStore
/// ViewStore acts as a state container, typically for some view over the application's central store.
/// You construct a ViewStore and pass it to a subview. Because it is Equatable, you can
/// make the subview Equatable as well, with `.equatable()`. The subview will then only render
/// when the actual value of the state changes.
struct ViewStore<LocalState, LocalAction>: Equatable
where LocalState: Equatable {
static func == (
lhs: ViewStore<LocalState, LocalAction>,
rhs: ViewStore<LocalState, LocalAction>
) -> Bool {
lhs.state == rhs.state
}
let state: LocalState
let send: (LocalAction) -> Void
}
/// Creates a tagged send function that can be used in a sub-view.
/// The returned send function will tag local view actions on the way out.
func address<Action, LocalAction>(
send: @escaping (Action) -> Void,
tag: @escaping (LocalAction) -> Action
) -> (LocalAction) -> Void {
return { localAction in
send(tag(localAction))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment