Redux-like 状态容器在 SwiftUI 中的应用教程

Redux-like 状态容器在 SwiftUI 中的应用教程

redux-like-state-container-in-swiftuiSample project for the series of posts about building Redux-like Single Source of Truth in SwiftUI.项目地址:https://gitcode.com/gh_mirrors/re/redux-like-state-container-in-swiftui

项目介绍

本项目旨在通过 SwiftUI 实现类似 Redux 的状态管理模式,提供单一数据源(Single Source of Truth),使得应用状态管理更加清晰和易于调试。项目灵感来源于 Redux、Elm 和 The Composable Architecture (TCA),并结合了 Swift 的并发模型。

项目快速启动

环境要求

  • Xcode 12 或更高版本
  • Swift 5.3 或更高版本

安装步骤

  1. 克隆项目仓库:

    git clone https://github.com/mecid/redux-like-state-container-in-swiftui.git
    
  2. 打开项目文件夹:

    cd redux-like-state-container-in-swiftui
    
  3. 打开 Xcode 项目文件:

    open ReduxLikeStateContainer.xcodeproj
    
  4. 在 Xcode 中选择合适的模拟器或连接的设备,然后运行项目。

示例代码

以下是一个简单的示例,展示如何在 SwiftUI 中使用 Redux-like 状态容器:

import SwiftUI
import Combine

// 定义状态
struct AppState {
    var counter: Int = 0
}

// 定义动作
enum AppAction {
    case increment
    case decrement
}

// 定义环境
struct AppEnvironment {
    var mainQueue: AnySchedulerOf<DispatchQueue> = .main
}

// 定义 Reducer
typealias AppReducer = Reducer<AppState, AppAction, AppEnvironment>

let appReducer: AppReducer = { state, action, environment in
    switch action {
    case .increment:
        state.counter += 1
        return Empty(completeImmediately: true).eraseToAnyPublisher()
    case .decrement:
        state.counter -= 1
        return Empty(completeImmediately: true).eraseToAnyPublisher()
    }
}

// 定义 Store
final class Store<State, Action, Environment>: ObservableObject {
    @Published private(set) var state: State
    private let environment: Environment
    private let reducer: AppReducer
    private var effectCancellables: Set<AnyCancellable> = []

    init(initialState: State, reducer: @escaping AppReducer, environment: Environment) {
        self.state = initialState
        self.reducer = reducer
        self.environment = environment
    }

    func send(_ action: Action) {
        let effects = self.reducer(&self.state, action, self.environment)
        effects.sink(receiveValue: { [weak self] in self?.send($0) })
              .store(in: &self.effectCancellables)
    }
}

// 定义视图
struct ContentView: View {
    @ObservedObject private var store: Store<AppState, AppAction, AppEnvironment>

    init(store: Store<AppState, AppAction, AppEnvironment>) {
        self.store = store
    }

    var body: some View {
        VStack {
            Text("Counter: \(store.state.counter)")
                .padding()
            Button("Increment") {
                store.send(.increment)
            }
            Button("Decrement") {
                store.send(.decrement)
            }
        }
    }
}

// 应用入口
@main
struct ReduxLikeStateContainerApp: App {
    let store = Store(initialState: AppState(), reducer: appReducer, environment: AppEnvironment())

    var body: some Scene {
        WindowGroup {
            ContentView(store: store)
        }
    }
}

应用案例和最佳实践

应用案例

  1. 计数器应用:如上示例代码所示,通过 Redux-like 状态容器管理计数器的状态。
  2. Todo 列表应用:使用 Redux-like 状态容器管理 Todo 列表的添加、删除和完成状态。

最佳实践

  1. 单一数据源:确保应用状态集中管理,避免状态分散导致的 bug。
  2. 纯函数 Reducer:Reducer 应该是纯函数,不产生

redux-like-state-container-in-swiftuiSample project for the series of posts about building Redux-like Single Source of Truth in SwiftUI.项目地址:https://gitcode.com/gh_mirrors/re/redux-like-state-container-in-swiftui

  • 20
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

万蝶娴Harley

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值