SwiftRedux is a Swift implementation of the Redux state container

Related tags

Utility SwiftRedux
Overview

Maintainability

SwiftRedux

SwiftRedux is a Swift implementation of the Redux state container. It relies on the same concepts and provides familiar Hooks through property wrappers.

Installation

SwiftRedux doesn't contain any external dependencies.

The only supported installation option is through Swift Package Manager:

Swift Package Manager

If you use Swift Package Manager, simply add SwiftRedux as a dependency of your package in Package.swift:

.package(url: "https://github.com/lucaslimapoa/SwiftRedux.git", from: "0.2.0")

Prerequisites

SwiftRedux relies on SwiftUI and Combine, so iOS 13 or later is required for it to work.

Usage

With SwiftRedux, the state of the app is kept inside a Store object. The Store is responsible for managing the state, updating the state through the use of reducers and handling logic, which can be handled my a middleware, for instance.

For starters, let's create a simple Counter app.

First, define a state for our app.

struct AppState: Equatable {
  var counter = 0
}

The AppState will hold the state for the whole app. Since this is a simple Counter app, the state will contain a simple count field. Now, we need a way to update the state. With SwiftRedux, the state can only be updated from Reducers. Reducers are objects that receive a dispatched action and the current state, the state is then updated based on the received action. Action are directly dispatched to the Store.

Let's create actions increasing and decreasing the counter now, so that our reducer can use it:

enum CounterAction {
  case increase
  case decrease
}

Now the reducer for the handling such actions can be created:

struct AppReducer: Reducer {
    func reduce(state: inout AppState, action: CounterAction) {
        switch action {
        case .increase:
            state.counter += 1
        case .decrease:
            state.counter -= 1
        }
    }
}

It's important to notice that the Reducer is sync, no async actions should be created or dispatched in the reducers.

Now that we have the AppState, CounterAction and AppReducer we can proceed and create a store:

let store = Store(
  initialState: AppState(),
  reducer: AppReducer()
)

Now all we have to do is to pass our store to the initial SwiftUI view, so the store can be put in the SwiftUI Environment and the Hooks (property wrappers) can be used.

ContentView()
  .store(store)

SwiftRedux provides a few Hooks so that the Store can be accessed. @Dispatch and @SelectState. The SwiftUI view would then look like this:

struct ContentView: View {
    @Dispatch<CounterAction> private var dispatch
    @SelectState(\AppState.counter) private var counter

    var body: some View {
        VStack {
            Stepper("Number of products", onIncrement: {
                dispatch(action: .increase)
            }, onDecrement: {
                dispatch(action: .decrease)
            })

            Text("The number of products is \(counter)")
        }
    }
}

Every time an action is dispatched and the state changes, the SwiftUI view will be updated and the counter property will have the new value from the store.

Advanced Usage

For looking into more advanced usage, please refer to the MovieDB-SwiftRedux app.

You might also like...
Swift Markdown is a Swift package for parsing, building, editing, and analyzing Markdown documents.

Swift Markdown is a Swift package for parsing, building, editing, and analyzing Markdown documents.

Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer documentation.

Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer docum

Cross-Platform, Protocol-Oriented Programming base library to complement the Swift Standard Library. (Pure Swift, Supports Linux)

SwiftFoundation Cross-Platform, Protocol-Oriented Programming base library to complement the Swift Standard Library. Goals Provide a cross-platform in

Swift - ✏️Swift 공부 저장소✏️

Swift 스위프트의 기초 1. Swift의 기본 2. 변수와 상수 [3. 데이터 타입 기본] [4. 데이터 타입 고급] 5. 연산자 6. 흐름 제어 7. 함수 8. 옵셔널 객체지향 프로그래밍과 스위프트 9. 구조체와 클래스 10. 프로퍼티와 메서드 11. 인스턴스 생

Swift-ndi - Swift wrapper around NewTek's NDI SDK

swift-ndi Swift wrapper around NewTek's NDI SDK. Make sure you extracted latest

__.swift is a port of Underscore.js to Swift.

__.swift Now, __.swift is version 0.2.0! With the chain of methods, __.swift became more flexible and extensible. Documentation: http://lotz84.github.

SNTabBarDemo-Swift - Cool TabBar With Swift
SNTabBarDemo-Swift - Cool TabBar With Swift

SNTabBarDemo-Swift Cool TabBar How To Use // MARK: - setup private func setu

Swift-when - Expression switch support in Swift

Swift When - supporting switch expressions in Swift! What is it? Basically, it a

Swift-compute-runtime - Swift runtime for Fastly Compute@Edge

swift-compute-runtime Swift runtime for Fastly Compute@Edge Getting Started Crea

Releases(0.2.0)
Owner
Lucas Lima
Computer Engineer. iOS Engineer and tech enthusiast.
Lucas Lima
Sovran-Swift: Small, efficient, easy. State Management for Swift

Sovran-Swift: Small, efficient, easy. State Management for Swift

Segment 5 Jan 3, 2023
🟣 Verge is a very tunable state-management engine on iOS App (UIKit / SwiftUI) and built-in ORM.

Verge is giving the power of state-management in muukii/Brightroom v2 development! Verge.swift ?? An effective state management architecture for iOS -

VergeGroup 478 Dec 29, 2022
Swift Server Implementation - RESTful APIs, AWS Lambda Serverless For Swift Runtime amazonlinux: AWS Lambda + API Gateway

Swift Server Implementation - RESTful APIs, AWS Lambda Serverless For Swift Runtime amazonlinux: AWS Lambda + API Gateway deployed on Graviton arm64 build swift:5.6.2-amazonlinux2-docker image

Furqan 2 Aug 16, 2022
Implementation of x-callback-url (Inter app communication) in swift

CallbackURLKit - Inter app communication Starting to integrate URL scheme in an app, why not be compliant with x-callback-url. CallbackURLKit.register

Eric Marchand 318 Nov 14, 2022
Swift implementation of the package url spec

PackageURL Swift implementation of the package url specification. Requirements Swift 5.3+ Usage import PackageURL let purl: PackageURL = "pkg:swift/a

Mattt 21 Jun 14, 2022
Swift implementation of AWS Lambda Events

Swift AWS Lambda Events Overview Swift AWS Lambda Runtime was designed to make building Lambda functions in Swift simple and safe. The library is an i

Swift on Server 29 Dec 19, 2022
Swift implementation of the QOI Format

Swift-QOI Swift implementation of the QOI Format. Contains extensions for AppKit and UIKit to integrate into your projects with ease. Documentation //

Amy While 18 Oct 21, 2022
Swift implementation of the QOI Format

Swift-QOI Swift implementation of the QOI Format. Contains extensions for AppKit and UIKit to integrate into your projects with ease. Documentation //

Amy While 1 Dec 9, 2021
The sample implementation of zip-archived document for a macOS AppKit platform.

The sample implementation of zip-archived document for a macOS AppKit platform. You can implement NSDocument-based I/O of archived document in your application like .sketch or .key.

usagimaru 4 Nov 12, 2022
BCSwiftTor - Opinionated pure Swift controller for Tor, including full support for Swift 5.5 and Swift Concurrency

BCSwiftTor Opinionated pure Swift controller for Tor, including full support for

Blockchain Commons, LLC — A “not-for-profit” benefit corporation 4 Oct 6, 2022