swift-persistence
Skill4 starsChanged 9 months agoMITView on GitHub
Implements a persistence layer using SwiftData or CoreData following MVVM — models, repository abstraction, and testable in-memory setup. Use when user says "add CoreData", "set up SwiftData", "persist data", "save to database", "add a data model", "create Core Data entities", or "use SwiftData models".
In this repository7 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- swift-architecture-auditSkill
- swift-code-reviewSkill
- swift-networkingSkill
- swift-project-setupSkill
- swift-testingSkill
- swiftui-componentSkill
The file
We split this skill into the rules it gives an agent
4 rules. About 0 are common, 3 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 16
Ask if not already specified:
- Distinctive: line 32
Ask: what entities are needed?
- Distinctive: line 58
Always define a protocol first so ViewModels can be tested with a mock:
- Very specific: line 124
Update TaskListViewModel to inject repository
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Swift Persistence
Instructions
Step 1: Choose the framework
Ask if not already specified:
SwiftData or CoreData?
| SwiftData | CoreData | |
| Min iOS | iOS 17+ | iOS 8+ |
| Syntax | @Model macro, Swift-native | NSManagedObject, Objective-C roots |
| Recommended for | New projects on iOS 17+ | Legacy projects, complex migration needs |
Then load the matching reference:
- SwiftData →
references/swiftdata.md - CoreData →
references/coredata.md
Step 2: Define the models
Ask: what entities are needed? For each entity:
- Name (singular, UpperCamelCase:
Task,UserProfile,Transaction) - Properties and their types
- Relationships to other entities (one-to-one, one-to-many, many-to-many)
- Any computed properties needed
Step 3: Generate the model layer
Models go in Core/Models/ — they are plain data types, framework-agnostic where possible.
Persistence infrastructure goes in Services/Storage/:
PersistenceController.swift— container setup, in-memory preview/test variant[Entity]Repository.swift— CRUD operations for each entity[Entity]RepositoryProtocol.swift— protocol for testability
Rule: ViewModels inject a repository protocol. They never touch ModelContext or NSManagedObjectContext directly.
Services/Storage/
├── PersistenceController.swift
├── TaskRepository.swift
└── TaskRepositoryProtocol.swiftStep 4: Generate the repository protocol
Always define a protocol first so ViewModels can be tested with a mock:
// Services/Storage/TaskRepositoryProtocol.swift
protocol TaskRepositoryProtocol {
func fetchAll() throws -> [Task]
func save(_ task: Task) throws
func delete(_ task: Task) throws
}Step 5: Wire into the ViewModel
ViewModels receive the repository via init:
@MainActor
@Observable
final class TaskListViewModel {
private(set) var tasks: [Task] = []
private let repository: TaskRepositoryProtocol
init(repository: TaskRepositoryProtocol = TaskRepository()) {
self.repository = repository
}
func loadTasks() {
tasks = (try? repository.fetchAll()) ?? []
}
}Step 6: Generate mock for tests
final class MockTaskRepository: TaskRepositoryProtocol {
var stubbedTasks: [Task] = []
var saveCallCount = 0
var deleteCallCount = 0
func fetchAll() throws -> [Task] { stubbedTasks }
func save(_ task: Task) throws { saveCallCount += 1 }
func delete(_ task: Task) throws { deleteCallCount += 1 }
}Step 7: Quality checklist
ModelContext/NSManagedObjectContextis never used in aViewModelorView- Repository protocol exists for every entity accessed by a ViewModel
- In-memory container/store exists for tests and previews
- Background context used for heavy writes (batch imports, migrations)
- Models in
Core/Models/have no direct framework import (SwiftDataorCoreData) in the ViewModel layer - Migrations are handled explicitly — no silent schema changes
Examples
Example 1: SwiftData task app
User says: "Add SwiftData to persist tasks with title, completion status, and due date"
Actions:
- Load
references/swiftdata.md - Generate
Taskmodel with@Model - Generate
PersistenceControllerwith.inMemorypreview variant - Generate
TaskRepository+TaskRepositoryProtocol - Update
TaskListViewModelto inject repository - Generate
MockTaskRepositoryfor tests
Example 2: CoreData in existing UIKit app
User says: "I need to add CoreData to my existing UIKit project to cache user profiles"
Actions:
- Load
references/coredata.md - Generate
UserProfileNSManagedObject subclass - Generate
PersistenceControllerwith in-memory option - Generate
UserProfileRepository+ protocol - Wire into existing
ProfileViewModel
Troubleshooting
SwiftData: "Context is not available" — ModelContext is being accessed outside a SwiftData-aware environment. Ensure the ModelContainer is set up at the App level and injected via .modelContainer() modifier. Never create contexts manually in ViewModels.
CoreData: merge conflicts — You are writing on the main context from a background thread. Use performBackgroundTask or a dedicated background context. Always call context.save() on the correct thread.
Tests failing because model can't be found — The in-memory store is not configured. Use PersistenceController.preview (SwiftData) or an in-memory NSPersistentContainer in your test setup.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

