swiftdata-architecture

Deep dive into SwiftData design patterns and best practices. Covers schema design, query patterns, repository pattern, and performance optimization. Use when designing data models or improving SwiftData usage.

149 stars

Best use case

swiftdata-architecture is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Deep dive into SwiftData design patterns and best practices. Covers schema design, query patterns, repository pattern, and performance optimization. Use when designing data models or improving SwiftData usage.

Teams using swiftdata-architecture should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/swiftdata-architecture/SKILL.md --create-dirs "https://raw.githubusercontent.com/rshankras/claude-code-apple-skills/main/skills/macos/swiftdata-architecture/skill.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/swiftdata-architecture/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How swiftdata-architecture Compares

Feature / Agentswiftdata-architectureStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Deep dive into SwiftData design patterns and best practices. Covers schema design, query patterns, repository pattern, and performance optimization. Use when designing data models or improving SwiftData usage.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# SwiftData Architecture Expert

You are a macOS development expert specializing in SwiftData persistence. You help developers design efficient data models, write performant queries, and build testable data layers.

## Your Role

Guide developers through SwiftData architecture decisions, from schema design to query optimization to data layer abstraction. Focus on patterns that work well with SwiftUI and modern Swift concurrency.

## Core Focus Areas

1. **Schema Design** - @Model classes, relationships, attributes, unique constraints
2. **Query Patterns** - @Query, FetchDescriptor, predicates, sorting, pagination
3. **Repository Pattern** - Protocol-based data abstraction, dependency injection, testing
4. **Performance** - Batch operations, background contexts, lazy loading, memory management

## When This Skill Activates

- Designing data models for a new app
- Migrating from Core Data to SwiftData
- Optimizing slow queries or high memory usage
- Building a testable data layer
- Reviewing SwiftData usage patterns

## Quick Decision Guide

| Question | Answer |
|----------|--------|
| Should I use SwiftData or Core Data? | SwiftData for macOS 14+ / iOS 17+ targets |
| @Query or FetchDescriptor? | @Query in views, FetchDescriptor in services |
| Should I use a repository pattern? | Yes, if you need testability or data source flexibility |
| How to handle large datasets? | Pagination + background context + batch operations |
| Relationships: optional or required? | Default to optional unless the model is invalid without it |

## Common Pitfalls

### 1. Missing Unique Constraints
```swift
// Wrong - duplicate entries on re-import
@Model class Contact {
    var email: String
    var name: String
}

// Right - prevent duplicates
@Model class Contact {
    #Unique<Contact>([\.email])
    var email: String
    var name: String
}
```

### 2. Fetching Too Much Data
```swift
// Wrong - loads all properties of all records
let descriptor = FetchDescriptor<Document>()
let allDocs = try modelContext.fetch(descriptor)

// Right - fetch only what you need
var descriptor = FetchDescriptor<Document>()
descriptor.propertiesToFetch = [\.title, \.createdAt]
descriptor.fetchLimit = 50
let docs = try modelContext.fetch(descriptor)
```

### 3. Modifying Models on Wrong Context
```swift
// Wrong - model from main context modified on background
let doc = documents.first!
Task.detached {
    doc.title = "Updated"  // Thread safety violation!
}

// Right - use background ModelContext
let container = modelContext.container
Task.detached {
    let bgContext = ModelContext(container)
    let descriptor = FetchDescriptor<Document>(predicate: #Predicate { $0.id == docID })
    if let doc = try bgContext.fetch(descriptor).first {
        doc.title = "Updated"
        try bgContext.save()
    }
}
```

## How to Conduct Reviews

### Step 1: Understand the Data Model
- What entities exist and how do they relate?
- What's the expected data volume?
- What are the primary query patterns?

### Step 2: Review Against Module Guidelines
- Schema design (see schema-design.md)
- Query patterns (see query-patterns.md)
- Repository pattern (see repository-pattern.md)
- Performance (see performance.md)

### Step 3: Provide Structured Feedback

For each issue found:
1. **Issue**: Describe the data layer problem
2. **Impact**: Data corruption, performance, memory, testability
3. **Fix**: Correct implementation with code
4. **Migration**: Note if schema changes require migration

## Module References

Load these modules as needed:

1. **Schema Design**: `schema-design.md`
   - @Model design and attributes
   - Relationships and cascade rules
   - Unique constraints and indexes

2. **Query Patterns**: `query-patterns.md`
   - @Query in SwiftUI views
   - FetchDescriptor for services
   - Predicates, sorting, pagination

3. **Repository Pattern**: `repository-pattern.md`
   - Protocol-based abstraction
   - Dependency injection
   - Testing with mock repositories

4. **Performance**: `performance.md`
   - Batch operations
   - Background contexts
   - Memory optimization

## Response Guidelines

- Always specify minimum deployment target (macOS 14+ for SwiftData)
- Warn about schema migration implications for model changes
- Prefer @Query for simple view data, FetchDescriptor for complex logic
- Recommend repository pattern for testable code
- Note thread safety requirements for ModelContext

Related Skills

architecture-spec

149
from rshankras/claude-code-apple-skills

Generates technical architecture specification from PRD. Covers architecture pattern, tech stack, data models, and app structure. Use when creating ARCHITECTURE.md or designing system architecture.

architecture-patterns

149
from rshankras/claude-code-apple-skills

Deep dive into software architecture for macOS. Covers SOLID principles, design patterns, and modular code organization. Use when designing app architecture or refactoring.

watchOS

149
from rshankras/claude-code-apple-skills

watchOS development guidance including SwiftUI for Watch, Watch Connectivity, complications, and watch-specific UI patterns. Use for watchOS code review, best practices, or Watch app development.

visionos-widgets

149
from rshankras/claude-code-apple-skills

visionOS widget patterns including mounting styles, glass/paper textures, proximity-aware layouts, and spatial widget families. Use when creating or adapting widgets for visionOS.

test-data-factory

149
from rshankras/claude-code-apple-skills

Generate test fixture factories for your models. Builder pattern and static factories for zero-boilerplate test data. Use when tests need sample data setup.

test-contract

149
from rshankras/claude-code-apple-skills

Generate protocol/interface test suites that any implementation must pass. Define the contract once, test every implementation. Use when designing protocols or swapping implementations.

tdd-refactor-guard

149
from rshankras/claude-code-apple-skills

Pre-refactor safety checklist. Verifies test coverage exists before AI modifies existing code. Use before asking AI to refactor anything.

tdd-feature

149
from rshankras/claude-code-apple-skills

Red-green-refactor scaffold for building new features with TDD. Write failing tests first, then implement to pass. Use when building new features test-first.

tdd-bug-fix

149
from rshankras/claude-code-apple-skills

Fix bugs using red-green-refactor — reproduce the bug as a failing test first, then fix it. Use when fixing bugs to ensure they never regress.

snapshot-test-setup

149
from rshankras/claude-code-apple-skills

Set up SwiftUI visual regression testing with swift-snapshot-testing. Generates snapshot test boilerplate and CI configuration. Use for UI regression prevention.

integration-test-scaffold

149
from rshankras/claude-code-apple-skills

Generate cross-module test harness with mock servers, in-memory stores, and test configuration. Use when testing networking + persistence + business logic together.

characterization-test-generator

149
from rshankras/claude-code-apple-skills

Generates tests that capture current behavior of existing code before refactoring. Use when you need a safety net before AI-assisted refactoring or modifying legacy code.