2026-10-21 18:16:29
在 iOS 开发中,主流架构模式如 MVVM 虽被广泛采用,但本文将介绍一种基于 ReSwift 和 Swift 语言特性(如 extension)构建的类似 Vue + Vuex 的单向数据流方案。这种方案借鉴了 Redux 的设计思想,更适合追求简单性和可测试性的团队。
在深入 ReSwift 之前,先回顾 iOS 端架构的演变历史:
Massive View ControllerApple 的 MVC 设计将大量逻辑放在 ViewController 中,导致代码臃肿、可维护性和可测试性差。
MVP引入 Presenter 层,分离业务逻辑,符合单一职责原则,解决了 Massive View Controller 问题。
MVVM类似 MVP,但引入双向数据绑定,成为当前 iOS 和 Android 最流行的架构。
VIPER更细化的模块化设计(View + Interactor + Presenter + Entity + Router),灵感来自 Clean Architecture,但被批评为过度工程。
ReSwift基于单向数据流,灵感来自 Redux,适合追求简单性和可测试性的团队。
ReSwift 是 Redux 的 Swift 实现,核心设计包括以下三部分:
The Store
单一数据结构管理整个应用的状态。
状态只能通过 dispatching Actions 修改。
状态变更后通知所有观察者(observers)。
Actions
描述状态变更的陈述性对象,不包含业务逻辑。
存储在 Store 中,转发给 Reducers 处理。
Reducers
基于当前 Action 和应用状态,通过纯函数返回新状态。
纯函数特性确保状态变更可预测。
以下是一个基于 ReSwift 的 iOS 项目结构及代码示例:
项目结构.├── App│ ├── AppDelegate.swift│ ├── AppState.swift│ └── AppReducer.swift├── Modules│ ├── Module1│ │ ├── State│ │ │ └── Module1State.swift│ │ ├── Reducers│ │ │ └── Module1Reducer.swift│ │ └── Actions│ │ └── Module1Action.swift│ └── Module2│ ├── State│ │ └── Module2State.swift│ ├── Reducers│ │ └── Module2Reducer.swift│ └── Actions│ └── Module2Action.swift代码实现AppDelegate.swift初始化全局 Store:
import UIKitimport ReSwiftlet mainStore = Store<AppState>( reducer: appReducer, state: nil)@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate { // ...}AppState.swift定义全局状态结构:
import ReSwiftstruct AppState: StateType { var module1State: Module1State var module2State: Module2State}AppReducer.swift组合子模块的 Reducer:
import ReSwiftimport ReSwiftRouterfunc appReducer(action: Action, state: AppState?) -> AppState { return AppState( module1State: module1Reducer(action: action, module1State: state?.module1State), module2State: module2Reducer(action: action, module2State: state?.module2State) )}Module1State.swift定义子模块状态:
import ReSwiftstruct Module1State { // 模块状态字段}Module1Reducer.swift处理子模块状态变更:
import ReSwiftfunc module1Reducer(action: Action, module1State: Module1State?) -> Module1State { return doSomething(module1State) ?? Module1State()}Module1Action.swift定义子模块的 Action:
import ReSwiftstruct Module1Action { func action1(params: Int) -> Action { return Action1(params: params) }}extension Module1Action { struct Action1: Action { let params: Int }}ReSwift 为 iOS 开发提供了一种类似 Vue + Vuex 的单向数据流方案,适合追求简单性和可测试性的团队。通过模块化设计和纯函数,状态管理更清晰、可维护性更高。后续文章将介绍如何结合 Coordinator、extension 和 VueLike 进一步优化开发体验。
下一篇预告:介绍 Coordinator 模式在 ReSwift 中的实践,解决路由管理问题。