swift-data
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSwiftData Best Practices — Modular MVVM-C Data Layer
SwiftData最佳实践 — 模块化MVVM-C数据层
Comprehensive data modeling, persistence, sync architecture, and error handling guide for SwiftData aligned with the clinic modular MVVM-C stack.
本指南为SwiftData提供了全面的数据建模、持久化、同步架构及错误处理方案,与诊所式模块化MVVM-C技术栈保持一致。
Architecture Alignment
架构对齐
This skill enforces the same modular architecture mandated by :
swift-ui-architect┌───────────────────────────────────────────────────────────────┐
│ Feature modules: View + ViewModel, no SwiftData imports │
├───────────────────────────────────────────────────────────────┤
│ Domain: models + repository/coordinator/error protocols │
├───────────────────────────────────────────────────────────────┤
│ Data: @Model entities, SwiftData stores, repository impls, │
│ remote clients, retry executor, sync queue, conflict handling │
└───────────────────────────────────────────────────────────────┘Key principle: SwiftData types (, , , ) live in Data-only implementation code. Feature Views/ViewModels work with Domain types and protocol dependencies.
@ModelModelContext@QueryFetchDescriptor本技能遵循规定的模块化架构:
swift-ui-architect┌───────────────────────────────────────────────────────────────┐
│ Feature modules: View + ViewModel, no SwiftData imports │
├───────────────────────────────────────────────────────────────┤
│ Domain: models + repository/coordinator/error protocols │
├───────────────────────────────────────────────────────────────┤
│ Data: @Model entities, SwiftData stores, repository impls, │
│ remote clients, retry executor, sync queue, conflict handling │
└───────────────────────────────────────────────────────────────┘核心原则: SwiftData类型(、、、)仅存在于数据层实现代码中。功能模块的View/ViewModel仅与领域层类型和协议依赖交互。
@ModelModelContext@QueryFetchDescriptorClinic 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 +
Domainonly (neverDesignSystem, never sibling features)Data - App target is the convergence point and owns , concrete coordinators, and Route Shell wiring
DependencyContainer - stays pure Swift and defines models plus repository,
Domain,*Coordinating, andErrorRoutingcontractsAppError - owns SwiftData/network/sync/retry/background I/O and implements Domain protocols
Data - 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 - 层为纯Swift代码,定义模型及仓库、
Domain、*Coordinating和ErrorRouting协议AppError - 层负责SwiftData/网络/同步/重试/后台I/O,并实现领域层协议
Data - 默认采用缓存优先读取和乐观队列写入的读写流程
- ViewModel直接调用仓库协议(默认不使用用例/交互器层)
When to Apply
适用场景
Reference these guidelines when:
- Defining @Model entity classes and mapping them to domain structs
- Setting up ModelContainer and ModelContext in the Data layer
- Implementing repository protocols backed by SwiftData
- Writing stale-while-revalidate repository reads ()
AsyncStream - Implementing optimistic writes plus queued sync operations
- Configuring entity relationships (one-to-many, inverse)
- Fetching from APIs and persisting to SwiftData via sync coordinators
- Handling save failures, corrupt stores, and migration errors
- Routing AppError traits to centralized error UI infrastructure
- Building preview infrastructure with sample data
- Planning schema migrations for app updates
在以下场景中参考本指南:
- 定义@Model实体类并将其映射到领域结构体
- 在数据层配置ModelContainer和ModelContext
- 实现基于SwiftData的仓库协议
- 编写缓存优先的仓库读取逻辑()
AsyncStream - 实现乐观写入及队列同步操作
- 配置实体关系(一对多、反向关联)
- 通过同步协调器从API获取数据并持久化到SwiftData
- 处理保存失败、存储损坏及迁移错误
- 将AppError特征路由到集中式错误UI基础设施
- 使用示例数据构建预览基础设施
- 为应用更新规划 Schema 迁移
Workflow
工作流程
Use this workflow when designing or refactoring a SwiftData-backed feature:
- Domain design: define domain structs (,
Trip) with validation/computed rules (seeFriend,model-domain-mapping)state-business-logic-placement - Entity design: define entity classes with mapping methods (see
@Model,model-*)model-domain-mapping - Repository protocol: define in Domain layer, implement with SwiftData in Data layer (see )
persist-repository-wrapper - Container wiring: configure once at the app boundary with error recovery (see
ModelContainer,persist-container-setup)persist-container-error-recovery - Dependency injection: inject repository protocols via @Environment (see )
state-dependency-injection - ViewModel: create @Observable ViewModel that delegates directly to repository protocols (see )
state-query-vs-viewmodel - CRUD flows: route all insert/delete/update through ViewModel -> Repository (see )
crud-* - Sync architecture: queue writes, execute via sync coordinator with retry policy (see )
sync-* - Relationships: model to-many relationships as arrays; define delete rules (see )
rel-* - Previews: create in-memory containers and sample data for fast iteration (see )
preview-* - Schema evolution: plan migrations with versioned schemas (see )
schema-*
在设计或重构基于SwiftData的功能时,遵循以下流程:
- 领域设计:定义领域结构体(如、
Trip)并添加验证/计算规则(参考Friend、model-domain-mapping)state-business-logic-placement - 实体设计:定义实体类并添加映射方法(参考
@Model、model-*)model-domain-mapping - 仓库协议:在领域层定义协议,在数据层基于SwiftData实现(参考)
persist-repository-wrapper - 容器配置:在应用边界一次性配置并添加错误恢复逻辑(参考
ModelContainer、persist-container-setup)persist-container-error-recovery - 依赖注入:通过@Environment注入仓库协议(参考)
state-dependency-injection - ViewModel:创建@Observable ViewModel,直接委托给仓库协议(参考)
state-query-vs-viewmodel - CRUD流程:所有增删改操作通过ViewModel -> Repository路由(参考)
crud-* - 同步架构:将写入操作加入队列,通过同步协调器结合重试策略执行(参考)
sync-* - 关系配置:将一对多关系建模为数组;定义删除规则(参考)
rel-* - 预览设置:创建内存容器和示例数据以加速迭代(参考)
preview-* - Schema演进:使用版本化Schema规划迁移(参考)
schema-*
Troubleshooting
故障排查
- Data not persisting -> ,
persist-model-macro,persist-container-setup,persist-autosaveschema-configuration - List not updating after background import -> ,
query-background-refreshpersist-model-actor - List not updating (same-context) -> ,
query-property-wrapperstate-wrapper-views - Duplicates from API sync -> ,
schema-unique-attributessync-conflict-resolution - App crashes on launch after model change -> ,
schema-migration-recoverypersist-container-error-recovery - Save failures silently losing data ->
crud-save-error-handling - Stale data from network -> ,
sync-offline-firstsync-fetch-persist - Widget/extension can't see data -> ,
persist-app-groupschema-configuration - Choosing architecture pattern for data views -> ,
state-query-vs-viewmodelpersist-repository-wrapper
- 数据未持久化 -> 、
persist-model-macro、persist-container-setup、persist-autosaveschema-configuration - 后台导入后列表未更新 -> 、
query-background-refreshpersist-model-actor - 同一上下文下列表未更新 -> 、
query-property-wrapperstate-wrapper-views - API同步导致重复数据 -> 、
schema-unique-attributessync-conflict-resolution - 模型变更后应用启动崩溃 -> 、
schema-migration-recoverypersist-container-error-recovery - 保存失败导致数据静默丢失 ->
crud-save-error-handling - 网络数据过期 -> 、
sync-offline-firstsync-fetch-persist - Widget/扩展无法读取数据 -> 、
persist-app-groupschema-configuration - 为数据视图选择架构模式 -> 、
state-query-vs-viewmodelpersist-repository-wrapper
Rule Categories by Priority
按优先级划分的规则类别
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Data Modeling | CRITICAL | |
| 2 | Persistence Setup | CRITICAL | |
| 3 | Querying & Filtering | HIGH | |
| 4 | CRUD Operations | HIGH | |
| 5 | Sync & Networking | HIGH | |
| 6 | Relationships | MEDIUM-HIGH | |
| 7 | SwiftUI State Flow | MEDIUM-HIGH | |
| 8 | Schema & Migration | MEDIUM-HIGH | |
| 9 | Sample Data & Previews | MEDIUM | |
| 优先级 | 类别 | 影响等级 | 前缀 |
|---|---|---|---|
| 1 | 数据建模 | 关键 | |
| 2 | 持久化设置 | 关键 | |
| 3 | 查询与过滤 | 高 | |
| 4 | CRUD操作 | 高 | |
| 5 | 同步与网络 | 高 | |
| 6 | 关系配置 | 中高 | |
| 7 | SwiftUI状态流 | 中高 | |
| 8 | Schema与迁移 | 中高 | |
| 9 | 示例数据与预览 | 中 | |
Quick Reference
快速参考
1. Data Modeling (CRITICAL)
1. 数据建模(关键)
- - Map @Model entities to domain structs across Domain/Data boundaries
model-domain-mapping - - Use custom types over parallel arrays
model-custom-types - - Use classes for SwiftData entity types
model-class-for-persistence - - Conform entities to Identifiable with UUID
model-identifiable - - Provide custom initializers for entity classes
model-initializer - - Use computed properties for derived data
model-computed-properties - - Provide sensible default values for entity properties
model-defaults - - Mark non-persistent properties with @Transient
model-transient - - Use external storage for large binary data
model-external-storage
- - 在领域/数据层边界将@Model实体映射到领域结构体
model-domain-mapping - - 使用自定义类型而非并行数组
model-custom-types - - 为SwiftData实体类型使用类
model-class-for-persistence - - 使实体遵循Identifiable协议并使用UUID
model-identifiable - - 为实体类提供自定义初始化方法
model-initializer - - 使用计算属性处理派生数据
model-computed-properties - - 为实体属性提供合理的默认值
model-defaults - - 使用@Transient标记非持久化属性
model-transient - - 为大型二进制数据使用外部存储
model-external-storage
2. Persistence Setup (CRITICAL)
2. 持久化设置(关键)
- - Wrap SwiftData behind Domain repository protocols
persist-repository-wrapper - - Apply @Model macro to all persistent types
persist-model-macro - - Configure ModelContainer at the App level
persist-container-setup - - Handle ModelContainer creation failure with store recovery
persist-container-error-recovery - - Access ModelContext via @Environment (Data layer)
persist-context-environment - - Enable autosave for manually created contexts
persist-autosave - - Use ModelContext.enumerate for large traversals
persist-enumerate-batch - - Use in-memory configuration for tests and previews
persist-in-memory-config - - Use App Groups for shared data storage
persist-app-group - - Use @ModelActor for background SwiftData work
persist-model-actor - - Pass PersistentIdentifier across actors
persist-identifier-transfer
- - 将SwiftData封装在领域仓库协议之后
persist-repository-wrapper - - 为所有持久化类型应用@Model宏
persist-model-macro - - 在App层面配置ModelContainer
persist-container-setup - - 通过存储恢复处理ModelContainer创建失败
persist-container-error-recovery - - 在数据层通过@Environment访问ModelContext
persist-context-environment - - 为手动创建的上下文启用自动保存
persist-autosave - - 使用ModelContext.enumerate处理大型遍历
persist-enumerate-batch - - 为测试和预览使用内存配置
persist-in-memory-config - - 使用App Groups实现数据共享存储
persist-app-group - - 使用@ModelActor处理后台SwiftData任务
persist-model-actor - - 在Actor之间传递PersistentIdentifier
persist-identifier-transfer
3. Querying & Filtering (HIGH)
3. 查询与过滤(高)
- - Use @Query for declarative data fetching (Data layer)
query-property-wrapper - - Force view refresh after background context inserts
query-background-refresh - - Apply sort descriptors to @Query
query-sort-descriptors - - Use #Predicate for type-safe filtering
query-predicates - - Use custom view initializers for dynamic queries
query-dynamic-init - - Use FetchDescriptor outside SwiftUI views
query-fetch-descriptor - - Tune FetchDescriptor paging and pending-change behavior
query-fetch-tuning - - Use localizedStandardContains for search
query-localized-search - - Use #Expression for reusable predicate components (iOS 18+)
query-expression
- - 在数据层使用@Query进行声明式数据获取
query-property-wrapper - - 后台上下文插入后强制刷新视图
query-background-refresh - - 为@Query应用排序描述符
query-sort-descriptors - - 使用#Predicate进行类型安全过滤
query-predicates - - 为动态查询使用自定义视图初始化方法
query-dynamic-init - - 在SwiftUI视图外使用FetchDescriptor
query-fetch-descriptor - - 调整FetchDescriptor的分页和待处理变更行为
query-fetch-tuning - - 使用localizedStandardContains实现搜索
query-localized-search - - 使用#Expression实现可复用的谓词组件(iOS 18+)
query-expression
4. CRUD Operations (HIGH)
4. CRUD操作(高)
- - Insert models via repository implementations
crud-insert-context - - Delete via repository with IndexSet from onDelete
crud-delete-indexset - - Use sheets for focused data creation via ViewModel
crud-sheet-creation - - Avoid orphaned records by persisting only on save
crud-cancel-delete - - Enable undo and use it to cancel edits
crud-undo-cancel - - Provide EditButton for list management
crud-edit-button - - Dismiss modal after ViewModel save completes
crud-dismiss-save - - Handle repository save failures with user feedback
crud-save-error-handling
- - 通过仓库实现插入模型
crud-insert-context - - 通过仓库处理onDelete的IndexSet删除操作
crud-delete-indexset - - 使用Sheet结合ViewModel实现聚焦式数据创建
crud-sheet-creation - - 仅在保存时持久化数据,避免孤立记录
crud-cancel-delete - - 启用撤销功能并用于取消编辑
crud-undo-cancel - - 提供EditButton用于列表管理
crud-edit-button - - ViewModel保存完成后关闭模态框
crud-dismiss-save - - 处理仓库保存失败并向用户反馈
crud-save-error-handling
5. Sync & Networking (HIGH)
5. 同步与网络(高)
- - Use injected sync services to fetch and persist API data
sync-fetch-persist - - Design offline-first architecture with repository reads and background sync
sync-offline-first - - Implement conflict resolution for bidirectional sync
sync-conflict-resolution
- - 使用注入的同步服务获取并持久化API数据
sync-fetch-persist - - 设计离线优先架构,结合仓库读取和后台同步
sync-offline-first - - 实现双向同步的冲突解决逻辑
sync-conflict-resolution
6. Relationships (MEDIUM-HIGH)
6. 关系配置(中高)
- - Use optionals for optional relationships
rel-optional-single - - Use arrays for one-to-many relationships
rel-array-many - - Rely on SwiftData automatic inverse maintenance
rel-inverse-auto - - Configure cascade delete rules for owned relationships
rel-delete-rules - - Sort relationship arrays explicitly
rel-explicit-sort
- - 为可选关系使用可选类型
rel-optional-single - - 为一对多关系使用数组
rel-array-many - - 依赖SwiftData自动维护反向关联
rel-inverse-auto - - 为所属关系配置级联删除规则
rel-delete-rules - - 显式排序关系数组
rel-explicit-sort
7. SwiftUI State Flow (MEDIUM-HIGH)
7. SwiftUI状态流(中高)
- - Route all data access through @Observable ViewModels
state-query-vs-viewmodel - - Place business logic in domain value types and repository-backed ViewModels
state-business-logic-placement - - Inject repository protocols via @Environment
state-dependency-injection - - Use @Bindable for two-way model binding
state-bindable - - Use @State for view-local transient data
state-local-state - - Extract wrapper views for dynamic query state
state-wrapper-views
- - 所有数据访问均通过@Observable ViewModel路由
state-query-vs-viewmodel - - 将业务逻辑放置在领域值类型和仓库驱动的ViewModel中
state-business-logic-placement - - 通过@Environment注入仓库协议
state-dependency-injection - - 使用@Bindable实现双向模型绑定
state-bindable - - 使用@State存储视图本地临时数据
state-local-state - - 提取包装视图处理动态查询状态
state-wrapper-views
8. Schema & Migration (MEDIUM-HIGH)
8. Schema与迁移(中高)
- - Define schema with all model types
schema-define-all-types - - Use @Attribute(.unique) for natural keys
schema-unique-attributes - - Use #Unique for compound uniqueness (iOS 18+)
schema-unique-macro - - Use #Index for hot predicates and sorts (iOS 18+)
schema-index - - Plan migrations before changing models
schema-migration-plan - - Plan migration recovery for schema changes
schema-migration-recovery - - Customize storage with ModelConfiguration
schema-configuration
- - 使用所有模型类型定义Schema
schema-define-all-types - - 为自然键使用@Attribute(.unique)
schema-unique-attributes - - 使用#Unique实现复合唯一性(iOS 18+)
schema-unique-macro - - 为高频谓词和排序使用#Index(iOS 18+)
schema-index - - 在修改模型前规划迁移方案
schema-migration-plan - - 为Schema变更规划迁移恢复策略
schema-migration-recovery - - 使用ModelConfiguration自定义存储
schema-configuration
9. Sample Data & Previews (MEDIUM)
9. 示例数据与预览(中)
- - Create a SampleData singleton for previews
preview-sample-singleton - - Use in-memory containers for preview isolation
preview-in-memory - - Define static sample data on model types
preview-static-data - - Annotate SampleData with @MainActor
preview-main-actor
- - 创建SampleData单例用于预览
preview-sample-singleton - - 使用内存容器实现预览隔离
preview-in-memory - - 在模型类型上定义静态示例数据
preview-static-data - - 为SampleData添加@MainActor注解
preview-main-actor
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
参考文件
| File | Description |
|---|---|
| references/_sections.md | Category definitions and ordering |
| assets/templates/_template.md | Template for new rules |
| metadata.json | Version and reference information |
| 文件 | 描述 |
|---|---|
| references/_sections.md | 类别定义与排序 |
| assets/templates/_template.md | 新规则模板 |
| metadata.json | 版本与参考信息 |