Swiftly manage and structure your SwiftUI application state with the Redux design pattern.
Redux SwiftUI Library is a robust framework designed to help developers manage app-wide state more predictably. By leveraging a single source of truth and a unidirectional flow of data, this library promotes more maintainable, debuggable, and scalable SwiftUI apps.

- Single Source of Truth: All of your app's state is stored in a single store, making debugging and state observation easier.
- Type Safety: Built with Swift's type system in mind, ensuring errors are caught at compile-time.
- Middleware Support: Enhance your store with custom middleware to handle side effects or introduce advanced logging and debugging tools.
- Thunks: Asynchronous actions are simplified with the use of thunks.
- Observable Store: Seamless integration with SwiftUI by making the store an observable object.
ReduxUI can be installed using Swift Package Manager.
- Open Your Project in Xcode: Start by opening your Swift project in Xcode.
- Add Package Dependency:
• Go to File → Swift Packages → Add Package Dependency.
• Paste the URL of the ReduxUI GitHub repository: https://github.com/kimnordin/ReduxUI.git. - Specify the Version: Choose the version of the ReduxUI package you want to add. You can specify a version number, a branch, or a commit.
- Add to Your Target: After Xcode loads the package and its dependencies, select the ReduxUI library, and add it to your project’s target(s).
- Define your App States:
// Main State of your App, containing all other States
struct AppState: StateType {
var userState: UserState = UserState()
}
struct UserState: StateType {
var name: String
}
- Set up your Actions:
struct UpdateUserName: Action {
let name: String
}
- Create the Reducers:
// Main Reducer handling Actions, updating the AppState accordingly
func appReducer(action: Action, state: AppState?) -> AppState {
let state = state ?? AppState()
return AppState(userState: userReducer(action: action, state: state.userState))
}
func userReducer(action: Action, state: UserState?) -> UserState {
var state = state ?? UserState()
switch action {
case let action as UpdateUserName:
state.name = action.name
default: break
}
return state
}
- Create a Store:
let store = Store<AppState>(state: AppState(), reducer: appReducer)
- Use within SwiftUI:
@EnvironmentObject private var store: Store<AppState>
- Dispatch Actions to modify the State:
store.dispatch(UpdateUserName(name: "Kim"))
- Middleware: Extend your store with custom functionalities.
- Thunks: Dispatch async actions and handle complex operations.
- The TestReduxUI Repository provides a simple Counter App made with the ReduxUI library.
- The WalkApp Repository highlights a more complex Step Counting App relying heavily on the ReduxUI library.