swift-data
28
总安装量
3
周安装量
#13204
全站排名
安装命令
npx skills add https://github.com/pproenca/dot-skills --skill swift-data
Agent 安装分布
claude-code
3
amp
2
opencode
2
kimi-cli
2
github-copilot
2
Skill 文档
Apple Developer SwiftData Best Practices
Comprehensive data modeling, persistence, and state management guide for Swift and SwiftUI applications using SwiftData, sourced from official Apple Developer tutorials and WWDC sessions. Contains 48 rules across 8 categories (after merging duplicates and adding concurrency coverage), prioritized by impact to guide automated refactoring and code generation.
When to Apply
Reference these guidelines when:
- Defining @Model classes and their properties
- Setting up ModelContainer and ModelContext for persistence
- Writing @Query declarations and predicates
- Implementing create, update, and delete operations
- Configuring model relationships (one-to-many, inverse)
- Coordinating SwiftUI state with SwiftData (@Bindable, @State, @Environment)
- Building preview infrastructure with sample data
- Planning schema migrations for app updates
Workflow
Use this workflow when designing or refactoring a SwiftData-backed feature:
- Model design: define
@Modelclasses, defaults, and transient/computed state (seemodel-*) - Container wiring: configure
ModelContaineronce at the app boundary; choose default vs custom configuration; decide App Group sharing (seepersist-container-setup,schema-configuration,persist-app-group) - Queries: prefer
@Queryin views; useFetchDescriptorin services/background work (seequery-property-wrapper,query-fetch-descriptor,query-fetch-tuning) - CRUD flows: insert/delete via the environment context; choose creation UI patterns; handle cancel/undo appropriately (see
crud-*) - Relationships: model to-many relationships as arrays; define delete rules for ownership (see
rel-*) - Previews: create in-memory containers and sample data for fast iteration (see
preview-*) - Schema evolution: plan migrations and validate uniqueness/indexing choices before shipping (see
schema-*)
Troubleshooting
- Data not persisting ->
persist-model-macro,persist-container-setup,persist-autosave,schema-configuration - List not updating ->
query-property-wrapper,state-wrapper-views - Duplicates ->
schema-unique-attributes,schema-unique-macro - Widget/extension canât see data ->
persist-app-group,schema-configuration
Rule Categories by Priority
| 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 | Relationships | MEDIUM-HIGH | rel- |
| 6 | SwiftUI State Flow | MEDIUM | state- |
| 7 | Sample Data & Previews | MEDIUM | preview- |
| 8 | Schema & Migration | LOW-MEDIUM | schema- |
Quick Reference
1. Data Modeling (CRITICAL)
model-custom-types– Use custom types over parallel arraysmodel-class-for-persistence– Use classes for SwiftData persistent modelsmodel-identifiable– Conform models to Identifiable with UUIDmodel-initializer– Provide custom initializers for model classesmodel-computed-properties– Use computed properties for derived datamodel-defaults– Provide sensible default values for model propertiesmodel-transient– Mark non-persistent properties with @Transientmodel-external-storage– Use external storage for large binary data
2. Persistence Setup (CRITICAL)
persist-model-macro– Apply @Model macro to all persistent typespersist-container-setup– Configure ModelContainer at the App levelpersist-context-environment– Access ModelContext via @Environmentpersist-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 actors
3. Querying & Filtering (HIGH)
query-property-wrapper– Use @Query for declarative data fetchingquery-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+)
4. CRUD Operations (HIGH)
crud-insert-context– Insert models via ModelContextcrud-delete-indexset– Delete using IndexSet with onDelete modifiercrud-sheet-creation– Use sheets for focused data creationcrud-cancel-delete– Delete unsaved models on cancelcrud-undo-cancel– Enable undo and use it to cancel editscrud-edit-button– Provide EditButton for list managementcrud-dismiss-save– Use Environment dismiss for modal save flow
5. Relationships (MEDIUM-HIGH)
rel-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 explicitly
6. SwiftUI State Flow (MEDIUM)
state-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 state
7. Sample Data & Previews (MEDIUM)
preview-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 @MainActor
8. Schema & Migration (LOW-MEDIUM)
schema-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-configuration– Customize storage with ModelConfiguration
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 |