swift-refactor

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Swift/SwiftUI Refactor (Modular MVVM-C)

Swift/SwiftUI 重构(模块化MVVM-C)

Comprehensive refactoring guide for migrating Swift/SwiftUI code to modular MVVM-C with local SPM package boundaries and App-target composition root wiring.
将Swift/SwiftUI代码迁移至带有本地SPM包边界和应用目标组合根配置的模块化MVVM-C架构的全面重构指南。

Mandated Architecture Stack

强制要求的架构栈

┌───────────────────────────────────────────────────────────────┐
│ App target: DependencyContainer, Coordinators, Route Shells   │
├───────────────────────────────────────────────────────────────┤
│ Feature modules: View + ViewModel (Domain + DesignSystem deps)│
├───────────────────────────────────────────────────────────────┤
│ Data package: repositories, remote/local stores, sync, retry  │
├───────────────────────────────────────────────────────────────┤
│ Domain package: models, repository/coordinator/error protocols │
└───────────────────────────────────────────────────────────────┘
Dependency Rule: Feature modules never import
Data
and never import sibling features.
┌───────────────────────────────────────────────────────────────┐
│ App target: DependencyContainer, Coordinators, Route Shells   │
├───────────────────────────────────────────────────────────────┤
│ Feature modules: View + ViewModel (Domain + DesignSystem deps)│
├───────────────────────────────────────────────────────────────┤
│ Data package: repositories, remote/local stores, sync, retry  │
├───────────────────────────────────────────────────────────────┤
│ Domain package: models, repository/coordinator/error protocols │
└───────────────────────────────────────────────────────────────┘
依赖规则:功能模块绝不能导入
Data
包,也不能导入同级功能模块。

Clinic Architecture Contract (iOS 26 / Swift 6.2)

诊所式架构规范(iOS 26 / Swift 6.2)

All guidance in this skill assumes the clinic modular MVVM-C architecture:
  • Feature modules import
    Domain
    +
    DesignSystem
    only (never
    Data
    , never sibling features)
  • App target is the convergence point and owns
    DependencyContainer
    , concrete coordinators, and Route Shell wiring
  • Domain
    stays pure Swift and defines models plus repository,
    *Coordinating
    ,
    ErrorRouting
    , and
    AppError
    contracts
  • Data
    owns SwiftData/network/sync/retry/background I/O and implements Domain protocols
  • Read/write flow defaults to stale-while-revalidate reads and optimistic queued writes
  • ViewModels call repository protocols directly (no default use-case/interactor layer)
本技能中的所有指导均基于诊所式模块化MVVM-C架构:
  • 功能模块仅导入
    Domain
    DesignSystem
    (绝不导入
    Data
    ,也不导入同级功能模块)
  • App目标是聚合点,负责
    DependencyContainer
    、具体协调器和路由外壳的配置
  • Domain
    保持纯Swift实现,定义模型以及仓库、
    *Coordinating
    ErrorRouting
    AppError
    协议
  • Data
    层负责SwiftData/网络/同步/重试/后台I/O操作,并实现Domain层定义的协议
  • 读写流程默认采用stale-while-revalidate读取机制和乐观队列写入机制
  • ViewModels直接调用仓库协议(无默认用例/交互器层)

When to Apply

适用场景

Reference these guidelines when:
  • Migrating from deprecated SwiftUI APIs (ObservableObject, NavigationView, old onChange)
  • Restructuring state management to use @Observable ViewModels
  • Adding @Equatable diffing to views for performance
  • Decomposing large views into 10-node maximum bodies
  • Refactoring navigation to coordinator + route shell pattern
  • Refactoring to Domain/Data/Feature/App package boundaries
  • Setting up dependency injection through
    DependencyContainer
  • Improving list/collection scroll performance
  • Replacing manual Task management with
    .task(id:)
    and cancellable loading
在以下场景中参考本指南:
  • 从已废弃的SwiftUI API(ObservableObject、NavigationView、旧版onChange)迁移
  • 重构状态管理以使用@Observable ViewModels
  • 为视图添加@Equatable diffing以提升性能
  • 将大型视图分解为最多包含10个节点的视图体
  • 将导航重构为协调器+路由外壳模式
  • 重构为Domain/Data/Feature/App包边界
  • 通过
    DependencyContainer
    设置依赖注入
  • 提升列表/集合的滚动性能
  • 使用
    .task(id:)
    和可取消加载替代手动Task管理

Non-Negotiable Constraints (iOS 26 / Swift 6.2)

不可协商的约束(iOS 26 / Swift 6.2)

  • @Observable
    ViewModels/coordinators,
    ObservableObject
    /
    @Published
    never
  • NavigationStack
    is owned by App-target route shells and coordinators
  • @Equatable
    macro on every view,
    AnyView
    never
  • Domain defines repository/coordinator/error-routing protocols; no framework-coupled I/O
  • No dedicated use-case/interactor layer; ViewModels call repository protocols directly
  • Views never access repositories directly
  • 必须使用
    @Observable
    ViewModels/协调器,绝不使用
    ObservableObject
    /
    @Published
  • NavigationStack
    由App目标的路由外壳和协调器管理
  • 每个视图都必须添加
    @Equatable
    宏,绝不使用
    AnyView
  • Domain层定义仓库/协调器/错误路由协议;不允许与框架耦合的I/O操作
  • 无专用用例/交互器层;ViewModels直接调用仓库协议
  • 视图绝不能直接访问仓库

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefixRules
1View Identity & DiffingCRITICAL
diff-
4
2API ModernizationCRITICAL
api-
7
3State ArchitectureCRITICAL
state-
6
4View CompositionHIGH
view-
7
5Navigation & CoordinationHIGH
nav-
5
6Layer ArchitectureHIGH
layer-
5
7Architecture PatternsHIGH
arch-
5
8Dependency InjectionMEDIUM-HIGH
di-
2
9Type Safety & ProtocolsMEDIUM-HIGH
type-
4
10List & Collection PerformanceMEDIUM
list-
4
11Async & Data FlowMEDIUM
data-
3
12Swift Language FundamentalsMEDIUM
swift-
8
优先级类别影响级别前缀规则数量
1视图标识与Diffing关键
diff-
4
2API现代化关键
api-
7
3状态架构关键
state-
6
4视图组合
view-
7
5导航与协调
nav-
5
6分层架构
layer-
5
7架构模式
arch-
5
8依赖注入中高
di-
2
9类型安全与协议中高
type-
4
10列表与集合性能
list-
4
11异步与数据流
data-
3
12Swift语言基础
swift-
8

Quick Reference

快速参考

1. View Identity & Diffing (CRITICAL)

1. 视图标识与Diffing(关键)

  • diff-equatable-views
    - Add @Equatable macro to every SwiftUI view
  • diff-closure-skip
    - Use @EquatableIgnored for closure properties
  • diff-identity-stability
    - Use stable O(1) identifiers in ForEach
  • diff-printchanges-debug
    - Use _printChanges() to diagnose re-renders
  • diff-equatable-views
    - 为每个SwiftUI视图添加@Equatable宏
  • diff-closure-skip
    - 对闭包属性使用@EquatableIgnored
  • diff-identity-stability
    - 在ForEach中使用稳定的O(1)标识符
  • diff-printchanges-debug
    - 使用_printChanges()诊断重渲染问题

2. API Modernization (CRITICAL)

2. API现代化(关键)

  • api-observable-macro
    - Migrate ObservableObject to @Observable macro
  • api-navigationstack-migration
    - Replace NavigationView with NavigationStack
  • api-onchange-signature
    - Migrate to new onChange signature
  • api-environment-object-removal
    - Replace @EnvironmentObject with @Environment
  • api-alert-confirmation-dialog
    - Migrate Alert to confirmationDialog API
  • api-list-foreach-identifiable
    - Replace id: .self with Identifiable conformance
  • api-toolbar-migration
    - Replace navigationBarItems with toolbar modifier
  • api-observable-macro
    - 将ObservableObject迁移至@Observable宏
  • api-navigationstack-migration
    - 用NavigationStack替代NavigationView
  • api-onchange-signature
    - 迁移至新版onChange签名
  • api-environment-object-removal
    - 用@Environment替代@EnvironmentObject
  • api-alert-confirmation-dialog
    - 将Alert迁移至confirmationDialog API
  • api-list-foreach-identifiable
    - 用Identifiable协议替代id: .self
  • api-toolbar-migration
    - 用toolbar修饰符替代navigationBarItems

3. State Architecture (CRITICAL)

3. 状态架构(关键)

  • state-scope-minimization
    - Minimize state scope to nearest consumer
  • state-derived-over-stored
    - Use computed properties over redundant @State
  • state-binding-extraction
    - Extract @Binding to isolate child re-renders
  • state-remove-observation
    - Migrate @ObservedObject to @Observable tracking
  • state-onappear-to-task
    - Replace onAppear closures with .task modifier
  • state-stateobject-placement
    - Migrate @StateObject to @State with @Observable
  • state-scope-minimization
    - 将状态范围最小化至最近的消费者
  • state-derived-over-stored
    - 使用计算属性替代冗余的@State
  • state-binding-extraction
    - 提取@Binding以隔离子视图重渲染
  • state-remove-observation
    - 将@ObservedObject迁移至@Observable追踪
  • state-onappear-to-task
    - 用.task修饰符替代onAppear闭包
  • state-stateobject-placement
    - 将@StateObject迁移至带@Observable的@State

4. View Composition (HIGH)

4. 视图组合(高)

  • view-extract-subviews
    - Extract subviews for diffing checkpoints
  • view-eliminate-anyview
    - Replace AnyView with @ViewBuilder or generics
  • view-computed-to-struct
    - Convert computed view properties to struct views
  • view-modifier-extraction
    - Extract repeated modifiers into custom ViewModifiers
  • view-conditional-content
    - Use Group or conditional modifiers over conditional views
  • view-preference-keys
    - Replace callback closures with PreferenceKey
  • view-body-complexity
    - Reduce view body to maximum 10 nodes
  • view-extract-subviews
    - 提取子视图作为diffing检查点
  • view-eliminate-anyview
    - 用@ViewBuilder或泛型替代AnyView
  • view-computed-to-struct
    - 将计算型视图属性转换为结构体视图
  • view-modifier-extraction
    - 将重复的修饰符提取为自定义ViewModifiers
  • view-conditional-content
    - 用Group或条件修饰符替代条件视图
  • view-preference-keys
    - 用PreferenceKey替代回调闭包
  • view-body-complexity
    - 将视图体复杂度降低至最多10个节点

5. Navigation & Coordination (HIGH)

5. 导航与协调(高)

  • nav-centralize-destinations
    - Refactor navigation to coordinator pattern
  • nav-value-based-links
    - Replace NavigationLink with coordinator routes
  • nav-path-state-management
    - Use NavigationPath for programmatic navigation
  • nav-split-view-adoption
    - Use NavigationSplitView for multi-column layouts
  • nav-sheet-item-pattern
    - Replace boolean sheet triggers with item binding
  • nav-centralize-destinations
    - 将导航重构为协调器模式
  • nav-value-based-links
    - 用协调器路由替代NavigationLink
  • nav-path-state-management
    - 使用NavigationPath实现程序化导航
  • nav-split-view-adoption
    - 对多列布局使用NavigationSplitView
  • nav-sheet-item-pattern
    - 用item绑定替代布尔值弹窗触发器

6. Layer Architecture (HIGH)

6. 分层架构(高)

  • layer-dependency-rule
    - Extract domain layer with zero framework imports
  • layer-usecase-protocol
    - Remove use-case/interactor layer; keep orchestration in ViewModel + repository protocols
  • layer-repository-protocol
    - Repository protocols in Domain, implementations in Data
  • layer-no-view-repository
    - Remove direct repository access from views
  • layer-viewmodel-boundary
    - Refactor ViewModels to expose display-ready state only
  • layer-dependency-rule
    - 提取零框架依赖的领域层
  • layer-usecase-protocol
    - 移除用例/交互器层;将编排逻辑保留在ViewModel+仓库协议中
  • layer-repository-protocol
    - 仓库协议定义在Domain层,实现放在Data层
  • layer-no-view-repository
    - 移除视图对仓库的直接访问
  • layer-viewmodel-boundary
    - 重构ViewModels使其仅暴露可直接用于展示的状态

7. Architecture Patterns (HIGH)

7. 架构模式(高)

  • arch-viewmodel-elimination
    - Restructure inline state into @Observable ViewModel
  • arch-protocol-dependencies
    - Extract protocol dependencies through ViewModel layer
  • arch-environment-key-injection
    - Use Environment keys for service injection
  • arch-feature-module-extraction
    - Extract features into independent modules
  • arch-model-view-separation
    - Extract business logic into Domain models and repository-backed ViewModels
  • arch-viewmodel-elimination
    - 将内联状态重构为@Observable ViewModel
  • arch-protocol-dependencies
    - 通过ViewModel层提取协议依赖
  • arch-environment-key-injection
    - 使用Environment键实现服务注入
  • arch-feature-module-extraction
    - 将功能提取为独立模块
  • arch-model-view-separation
    - 将业务逻辑提取至Domain模型和仓库驱动的ViewModels

8. Dependency Injection (MEDIUM-HIGH)

8. 依赖注入(中高)

  • di-container-composition
    - Compose dependency container at app root
  • di-mock-testing
    - Add mock implementation for every protocol dependency
  • di-container-composition
    - 在应用根节点组合依赖容器
  • di-mock-testing
    - 为每个协议依赖添加Mock实现

9. Type Safety & Protocols (MEDIUM-HIGH)

9. 类型安全与协议(中高)

  • type-tagged-identifiers
    - Replace String IDs with tagged types
  • type-result-over-optionals
    - Use Result type over optional with error flag
  • type-phantom-types
    - Use phantom types for compile-time state machines
  • type-force-unwrap-elimination
    - Eliminate force unwraps with safe alternatives
  • type-tagged-identifiers
    - 用标记类型替代String类型的ID
  • type-result-over-optionals
    - 使用Result类型替代带错误标记的可选值
  • type-phantom-types
    - 使用幽灵类型实现编译时状态机
  • type-force-unwrap-elimination
    - 使用安全替代方案消除强制解包

10. List & Collection Performance (MEDIUM)

10. 列表与集合性能(中)

  • list-constant-viewcount
    - Ensure ForEach produces constant view count per element
  • list-filter-in-model
    - Move filter/sort logic from ForEach into ViewModel
  • list-lazy-stacks
    - Replace VStack/HStack with Lazy variants for unbounded content
  • list-id-keypath
    - Provide explicit id keyPath — never rely on implicit identity
  • list-constant-viewcount
    - 确保ForEach为每个元素生成固定数量的视图
  • list-filter-in-model
    - 将过滤/排序逻辑从ForEach移至ViewModel
  • list-lazy-stacks
    - 对无界内容用Lazy变体替代VStack/HStack
  • list-id-keypath
    - 提供显式的id键路径——绝不依赖隐式标识

11. Async & Data Flow (MEDIUM)

11. 异步与数据流(中)

  • data-task-modifier
    - Replace onAppear async work with .task modifier
  • data-error-loadable
    - Model loading states as enum instead of boolean flags
  • data-cancellation
    - Use .task automatic cancellation — never manage Tasks manually
  • data-task-modifier
    - 用.task修饰符替代onAppear中的异步操作
  • data-error-loadable
    - 用枚举建模加载状态,替代布尔标记
  • data-cancellation
    - 使用.task自动取消——绝不手动管理Tasks

12. Swift Language Fundamentals (MEDIUM)

12. Swift语言基础(中)

  • swift-let-vs-var
    - Use let for constants, var for variables
  • swift-structs-vs-classes
    - Prefer structs over classes
  • swift-camel-case-naming
    - Use camelCase naming convention
  • swift-string-interpolation
    - Use string interpolation for dynamic text
  • swift-functions-clear-names
    - Name functions and parameters for clarity
  • swift-for-in-loops
    - Use for-in loops for collections
  • swift-optionals
    - Handle optionals safely with unwrapping
  • swift-closures
    - Use closures for inline functions
  • swift-let-vs-var
    - 用let定义常量,var定义变量
  • swift-structs-vs-classes
    - 优先使用结构体而非类
  • swift-camel-case-naming
    - 使用驼峰命名法
  • swift-string-interpolation
    - 使用字符串插值处理动态文本
  • swift-functions-clear-names
    - 为函数和参数命名时保证清晰性
  • swift-for-in-loops
    - 对集合使用for-in循环
  • swift-optionals
    - 安全处理可选值的解包
  • swift-closures
    - 使用闭包实现内联函数

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • Section definitions - Category structure and impact levels
  • Rule template - Template for adding new rules
阅读单个参考文件获取详细说明和代码示例:
  • 章节定义 - 类别结构和影响级别
  • 规则模板 - 添加新规则的模板

Reference Files

参考文件

FileDescription
references/_sections.mdCategory definitions and ordering
assets/templates/_template.mdTemplate for new rules
文件描述
references/_sections.md类别定义与排序
assets/templates/_template.md新规则模板