技能创建器
skill-creator
创建、改进和评估自定义技能,把专业流程转化为可重复使用的 AI 能力。
swift-data【数据与研究】SwiftData persistence and data-layer architecture for iOS 26 / Swift 6.2 clinic modular MVVM-C apps. Use when writing, reviewing, or refactoring @Model entities, repository implementations, stale-while-revalidate reads, optimistic queued writes, sync/retry behavior, and SwiftUI integration that keeps SwiftData types inside Data-only boundaries.
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
Comprehensive data modeling, persistence, sync architecture, and error handling guide for SwiftData aligned with the clinic modular MVVM-C stack.
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 (@Model, ModelContext, @Query, FetchDescriptor) live in Data-only implementation code. Feature Views/ViewModels work with Domain types and protocol dependencies.
All guidance in this skill assumes the clinic modular MVVM-C architecture:
Domain + DesignSystem only (never Data, never sibling features)DependencyContainer, concrete coordinators, and Route Shell wiringDomain stays pure Swift and defines models plus repository, *Coordinating, ErrorRouting, and AppError contractsData owns SwiftData/network/sync/retry/background I/O and implements Domain protocolsReference these guidelines when:
AsyncStream)Use this workflow when designing or refactoring a SwiftData-backed feature:
Trip, Friend) with validation/computed rules (see model-domain-mapping, state-business-logic-placement)@Model entity classes with mapping methods (see model-*, model-domain-mapping)persist-repository-wrapper)ModelContainer once at the app boundary with error recovery (see persist-container-setup, persist-container-error-recovery)state-dependency-injection)state-query-vs-viewmodel)crud-*)sync-*)rel-*)preview-*)schema-*)persist-model-macro, persist-container-setup, persist-autosave, schema-configurationquery-background-refresh, persist-model-actorquery-property-wrapper, state-wrapper-viewsschema-unique-attributes, sync-conflict-resolutionschema-migration-recovery, persist-container-error-recoverycrud-save-error-handlingsync-offline-first, sync-fetch-persistpersist-app-group, schema-configurationstate-query-vs-viewmodel, persist-repository-wrapper| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Data Modeling | CRITICAL | model- |
| 2 | Persistence Setup | CRITICAL | persist- |
| 3 | Querying & Filtering | HIGH | query- |
| 4 | CRUD Operations | HIGH | crud- |
| 5 | Sync & Networking | HIGH | sync- |
| 6 | Relationships | MEDIUM-HIGH | rel- |
| 7 | SwiftUI State Flow | MEDIUM-HIGH | state- |
| 8 | Schema & Migration | MEDIUM-HIGH | schema- |
| 9 | Sample Data & Previews | MEDIUM | preview- |
model-domain-mapping - Map @Model entities to domain structs across Domain/Data boundariesmodel-custom-types - Use custom types over parallel arraysmodel-class-for-persistence - Use classes for SwiftData entity typesmodel-identifiable - Conform entities to Identifiable with UUIDmodel-initializer - Provide custom initializers for entity classesmodel-computed-properties - Use computed properties for derived datamodel-defaults - Provide sensible default values for entity propertiesmodel-transient - Mark non-persistent properties with @Transientmodel-external-storage - Use external storage for large binary datapersist-repository-wrapper - Wrap SwiftData behind Domain repository protocolspersist-model-macro - Apply @Model macro to all persistent typespersist-container-setup - Configure ModelContainer at the App levelpersist-container-error-recovery - Handle ModelContainer creation failure with store recoverypersist-context-environment - Access ModelContext via @Environment (Data layer)persist-autosave - Enable autosave for manually created contextspersist-enumerate-batch - Use ModelContext.enumerate for large traversalspersist-in-memory-config - Use in-memory configuration for tests and previewspersist-app-group - Use App Groups for shared data storagepersist-model-actor - Use @ModelActor for background SwiftData workpersist-identifier-transfer - Pass PersistentIdentifier across actorsquery-property-wrapper - Use @Query for declarative data fetching (Data layer)query-background-refresh - Force view refresh after background context insertsquery-sort-descriptors - Apply sort descriptors to @Queryquery-predicates - Use #Predicate for type-safe filteringquery-dynamic-init - Use custom view initializers for dynamic queriesquery-fetch-descriptor - Use FetchDescriptor outside SwiftUI viewsquery-fetch-tuning - Tune FetchDescriptor paging and pending-change behaviorquery-localized-search - Use localizedStandardContains for searchquery-expression - Use #Expression for reusable predicate components (iOS 18+)crud-insert-context - Insert models via repository implementationscrud-delete-indexset - Delete via repository with IndexSet from onDeletecrud-sheet-creation - Use sheets for focused data creation via ViewModelcrud-cancel-delete - Avoid orphaned records by persisting only on savecrud-undo-cancel - Enable undo and use it to cancel editscrud-edit-button - Provide EditButton for list managementcrud-dismiss-save - Dismiss modal after ViewModel save completescrud-save-error-handling - Handle repository save failures with user feedbacksync-fetch-persist - Use injected sync services to fetch and persist API datasync-offline-first - Design offline-first architecture with repository reads and background syncsync-conflict-resolution - Implement conflict resolution for bidirectional syncrel-optional-single - Use optionals for optional relationshipsrel-array-many - Use arrays for one-to-many relationshipsrel-inverse-auto - Rely on SwiftData automatic inverse maintenancerel-delete-rules - Configure cascade delete rules for owned relationshipsrel-explicit-sort - Sort relationship arrays explicitlystate-query-vs-viewmodel - Route all data access through @Observable ViewModelsstate-business-logic-placement - Place business logic in domain value types and repository-backed ViewModelsstate-dependency-injection - Inject repository protocols via @Environmentstate-bindable - Use @Bindable for two-way model bindingstate-local-state - Use @State for view-local transient datastate-wrapper-views - Extract wrapper views for dynamic query stateschema-define-all-types - Define schema with all model typesschema-unique-attributes - Use @Attribute(.unique) for natural keysschema-unique-macro - Use #Unique for compound uniqueness (iOS 18+)schema-index - Use #Index for hot predicates and sorts (iOS 18+)schema-migration-plan - Plan migrations before changing modelsschema-migration-recovery - Plan migration recovery for schema changesschema-configuration - Customize storage with ModelConfigurationpreview-sample-singleton - Create a SampleData singleton for previewspreview-in-memory - Use in-memory containers for preview isolationpreview-static-data - Define static sample data on model typespreview-main-actor - Annotate SampleData with @MainActorRead individual reference files for detailed explanations and code examples:
| File | Description |
|---|---|
| references/_sections.md | Category definitions and ordering |
| assets/templates/_template.md | Template for new rules |
| metadata.json | Version and reference information |