Logo Swiftdata

Swiftdata

Cộng đồng
robbyt
swiftdata

This skill should be used when working with SwiftData — @Model definitions, @Query, @Relationship, ModelContext, ModelContainer, schema migration, Swift 6 concurrency, performance optimization, or architecture review. Also triggers on: "SwiftData audit", "@Model issues", "SwiftData crashes", "predicate problems", "background context patterns", "N+1 queries", "SwiftData vs SQLiteData vs GRDB", "CloudKit sync with SwiftData", "SwiftData migration fails", or "SwiftData migration diagnostics". Covers auditing existing code, writing new SwiftData code, migration debugging, and architecture review.

Tổng quan

Nhà phát hànhrobbyt
Kho mãclaude-skills
Tên kỹ năngswiftdata
Sao
42
Bản fork
2
Tệp đi kèm
11
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • 11 tệp đi kèm

    Các tập lệnh, mẫu và tài liệu tham khảo mà mô hình có thể đọc khi làm việc. Các tệp chỉ cho phép đọc và không bao giờ được thực thi.

  • Mã nguồn mở

    Được robbyt công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Swiftdata trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/robbyt/claude-skills/tree/main/plugins/swift/skills/swiftdata
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/robbyt/claude-skills.git /tmp/claude-skills
mkdir -p .claude/skills
cp -r /tmp/claude-skills/plugins/swift/skills/swiftdata .claude/skills/swiftdata
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Swiftdata trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Swiftdata ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Swiftdata không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

SwiftData — Architecture, Patterns, and Audit Guide

Swift 6 strict concurrency only. No Swift 5 patterns.

Decision: SwiftData vs SQLiteData vs GRDB

NeedChooseWhy
Simple local CRUD + SwiftUISwiftDataNative integration, @Query, automatic observation
Complex queries, JOINs, FTSGRDBFull SQL access, 11 years battle-tested
SwiftData ergonomics + SQL powerSQLiteData@Table structs, @FetchAll, CloudKit sharing support
Cross-platform (Android/Linux)GRDB or raw SQLiteNo Apple framework dependency
CloudKit shared databasesSQLiteData or Core DataSwiftData only supports private CloudKit databases

SwiftData is viable for production IF the patterns in this guide are followed. Most "SwiftData is broken" complaints trace to bad data modeling or missing abstractions, not framework bugs.

Core Rules (Non-Negotiable)

These five rules prevent the most common crashes and data corruption. Violating any one is a critical-severity finding. For detailed code examples, consult references/core-rules.md.

1. @Model must be final class — never struct

@Model struct compiles but crashes at runtime or silently corrupts data. Always use @Model final class (omit final only for class inheritance on iOS 26+).

2. Never pass @Model objects across actor boundaries

ModelContainer and PersistentIdentifier are Sendable. Everything else is not. Pass persistentModelID, re-fetch on the target context.

3. Always use repository pattern with DTOs

The single architectural decision that determines success or failure with SwiftData. Views never touch @Model directly — repositories return Sendable DTOs, accept PersistentIdentifier for mutations. See references/core-rules.md for the full pattern.

4. Version your schema from the first release

Every @Model class MUST appear in its VersionedSchema.models array. Missing models are silently dropped during migration — permanent data loss. See references/migration.md.

5. Call save() explicitly for critical data

Main context autosaves on runloop idle. Background contexts have autosaveEnabled = false. On macOS, closing a window can lose unsaved main context changes. Always call try context.save() after mutations.

Model Design Quick Reference

Macro/PatternPurposeNotes
@Attribute(.unique)Upsert on collisionPrimitives only
@Attribute(.externalStorage)External file for large dataMandatory for images/audio data
@Attribute(originalName:)Rename property, preserve dataEnables lightweight migration
@TransientNot persistedMust have default value. Cannot appear in predicates
#Unique<T>([\.a, \.b])Compound uniquenessiOS 18+
#Index<T>([\.a], [\.b])Compound/single indexesiOS 18+. Index predicate/sort properties only
.cascade delete ruleDelete parent deletes childrenUse for owned relationships
.nullify delete ruleSets child reference to nilDefault. Crashes if child property is non-optional

For relationship initialization, enum workarounds, binary data patterns, and Codable struct hazards, consult references/model-patterns.md.

Predicate Safety Summary

Safe in #Predicate: String operations (localizedStandardContains, starts(with:)), numeric/date comparisons, relationship traversal ($0.album?.title), Bool checks, nil checks, compound conditions.

Compiles but CRASHES: Enum properties (even RawRepresentable), @Transient properties, computed properties, generic predicates (Release builds only), optional to-many relationships, contents of value-type arrays ([String]), sub-properties of Codable structs.

For the full safe/crash pattern catalog and dynamic @Query patterns, consult references/predicates-and-queries.md.

Concurrency (Swift 6 Strict)

Use @ModelActor for background work. Create with Task.detached to avoid running on main thread. Communicate across actors via PersistentIdentifier and Sendable DTOs only. For detailed patterns and gotchas, consult references/concurrency.md.

Performance Essentials

  • N+1 prevention: Use relationshipKeyPathsForPrefetching on FetchDescriptor
  • Batch operations: Chunk inserts into batches of 500-1000, save each chunk
  • Indexing: 2-3 indexes per model on queried/sorted properties. Each index slows writes
  • Prefer FetchDescriptor over @Query for non-trivial work (fetchLimit, fetchOffset, propertiesToFetch, error handling)
  • Profiling: -com.apple.CoreData.SQLDebug 3 for EXPLAIN QUERY PLAN

For complete performance patterns, batch operation code, and profiling techniques, consult references/performance.md.

Schema Migration

Lightweight migration handles: adding optional properties, removing properties, renaming with @Attribute(originalName:), adding new models. Custom migration required for: type changes, non-optional without defaults, data transformations, deduplication.

Critical migration rules:

  1. Data access goes in willMigrate, NOT didMigrate
  2. Every @Model class must appear in its VersionedSchema.models array
  3. Non-optional Codable properties block ALL future migrations (confirmed bug FB22151570)
  4. Do NOT specify a SchemaMigrationPlan if implicit lightweight migration would suffice
  5. Test migrations on real on-disk stores, not in-memory configurations

For complete migration patterns (including two-stage migration for type changes, many-to-many migration, junction table metadata, and deduplication), consult references/migration.md.

Migration Diagnostics

When a migration fails, crashes, or loses data:

Error MessageLikely CauseFix
"Expected only Arrays for Relationships"Many-to-many inverse missingAdd @Relationship(inverse:)
"incompatible model" / crash on launchSchema version mismatchVerify migration plan schemas array
"Failed to fulfill faulting for..."Relationship integrity brokenPrefetch relationships during migration
Data gone after migrationUsed didMigrate for old modelsMove data access to willMigrate
Simulator works, device crashesSimulator deletes DB on rebuildTest on real device with real data

For the complete diagnostic decision tree, step-by-step debugging protocol, verification checklists, and escalation procedures, consult references/migration-diagnostics.md.

CloudKit Integration

SwiftData supports automatic CloudKit sync to private databases. All properties must be optional or have default values. All relationships must be optional. SwiftData uses last-write-wins conflict resolution by default. For full CloudKit patterns, constraints, sync status monitoring, and tvOS considerations, consult references/cloudkit.md.

Audit Checklist

When reviewing SwiftData code, check in order of severity. Calculate risk: CRITICAL x 3 + HIGH x 2 + MEDIUM x 1 (cap at 10).

CRITICAL (crash or data loss): @Model struct, missing models in VersionedSchema, array relationship without = [], fetch in didMigrate, enum in #Predicate

HIGH (data races, silent corruption): Background Task using @Environment modelContext, missing save() in background contexts, updating both sides of inverse relationship, passing @Model across actor boundary, relationship assignment inside init()

MEDIUM (performance): N+1 relationship access in loops, 5+ indexes on one model, bulk insert without chunking, @Query with >1000 results, large Data without .externalStorage

For the full audit table with detection patterns, fixes, false positives, and risk scoring, consult references/audit-checklist.md.

Known Bugs by iOS Version

  • iOS 17.0-17.1: Avoid if possible. Enum predicate crashes, broken didSave/willSave, @ModelActor mutations don't trigger @Query updates
  • iOS 17.2+: Minimum recommended target. Optional predicate chains still unreliable
  • iOS 18.0: Major refactoring broke some iOS 17 patterns. Releasing @ModelActor destroys fetched instances. #Expression macro added
  • iOS 18.x+: #Index and #Unique macros. Multi-store support
  • Xcode 26 / iOS 26: Model inheritance. Backported to iOS 17: @ModelActor triggers @Query updates, Codable in predicates

For the full active bugs list and version-specific details, consult references/known-bugs.md.

Testing

Use in-memory ModelConfiguration for unit tests. Tests cannot run in parallel — use @MainActor on test classes. For preview support, inject mock repositories via Environment. For testing patterns, consult references/testing.md.

Additional Resources

Reference Files

All detailed content lives in references/:

  • references/core-rules.md — Detailed code for the 5 non-negotiable rules, repository pattern, DTO pattern
  • references/model-patterns.md — Relationships, enums, properties, binary data, Codable hazards, class inheritance
  • references/concurrency.md — @ModelActor, cross-actor communication, Swift 6 patterns
  • references/predicates-and-queries.md — Safe/crash predicate patterns, dynamic @Query, FetchDescriptor
  • references/performance.md — N+1, batch ops, indexing, profiling, memory optimization
  • references/migration.md — VersionedSchema, migration plans, two-stage migration, many-to-many, deduplication
  • references/migration-diagnostics.md — Diagnostic decision tree, error-to-fix mapping, verification, escalation
  • references/cloudkit.md — CloudKit sync, constraints, conflict resolution, tvOS, sharing
  • references/audit-checklist.md — Full audit tables with detection patterns and risk scoring
  • references/known-bugs.md — iOS version bugs, active bugs, workarounds
  • references/testing.md — Test setup, repository mocking, migration testing on real devices

WWDC References

  • 2023-10187: Meet SwiftData
  • 2023-10195: Model your schema with SwiftData
  • 2023-10196: Dive deeper into SwiftData
  • 2023-10154: Build an app with SwiftData
  • 2024-10137: What's new in SwiftData
  • 2025-10138: SwiftData updates (model inheritance, backports)

Community Resources

  • fatbobman.com — Most thorough SwiftData analysis
  • blog.jacobstechtavern.com — Performance profiling
  • pado.name — "@Query Considered Harmful" (repository pattern motivation)
  • wadetregaskis.com — Comprehensive pitfalls catalog
  • donnywals.com — Migration deep dives
  • pointfree.co — SQLiteData as alternative

Tệp đi kèm

Mô hình đọc các tệp này khi cần trong lúc kỹ năng được tải. Các tệp được cung cấp ở dạng có thể đọc và không bao giờ được thực thi.

Câu hỏi thường gặp

Kỹ năng AI Swiftdata làm được gì?

This skill should be used when working with SwiftData — @Model definitions, @Query, @Relationship, ModelContext, ModelContainer, schema migration, Swift 6 concurrency, performance optimization, or architecture review. Also triggers on: "SwiftData audit", "@Model issues", "SwiftData crashes", "predicate problems", "background context patterns", "N+1 queries", "SwiftData vs SQLiteData vs GRDB", "CloudKit sync with SwiftData", "SwiftData migration fails", or "SwiftData migration diagnostics". Covers auditing existing code, writing new SwiftData code, migration debugging, and architecture review.

Vì sao nên dùng Swiftdata trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Swiftdata là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Swiftdata trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/robbyt/claude-skills/tree/main/plugins/swift/skills/swiftdata. TypingMind đọc tệp SKILL.md, đóng gói các tệp đi kèm và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Swiftdata?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Swiftdata với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Swiftdata với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Swiftdata có miễn phí không?

Kỹ năng này được robbyt phát hành trên GitHub. Hãy xem điều khoản giấy phép trong kho mã. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇