Przejdź do treści
Biblioteka skilli
Programowanie · Planowanie

swiftdata-persistence-expert

/swiftdata-persistence-expert

Projektuje architekturę trwałości w SwiftData i Core Data, synchronizację CloudKit oraz bezpieczne migracje między wersjami schematu.

Repozytorium
ios-cli ↗
Licencja
MIT
Ostatnia zmiana repozytorium
09.11.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
1
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 09.11.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co robi i kiedy

Projektuje architekturę trwałości w SwiftData i Core Data, synchronizację CloudKit oraz bezpieczne migracje między wersjami schematu.

Oryginalny opis (EN)

SwiftData and Core Data persistence architecture, schema design, model relationships, CloudKit sync, and safe multi-version database migrations (VersionedSchema & SchemaMigrationPlan). Use when designing data persistence, fixing store corruption, or upgrading app schema between releases.

Jak działa

  1. 1. Schema Design Standards (@Model)
  2. 2. Safe Schema Migrations (VersionedSchema & SchemaMigrationPlan)
  3. 3. Concurrency with SwiftData (@ModelActor)
  4. 4. SwiftData Verification Checklist
Sekcje z nagłówków SKILL.md, w oryginale · 147 linii, 634 słów
Podgląd SKILL.md
---
name: swiftdata-persistence-expert
description: SwiftData and Core Data persistence architecture, schema design, model relationships, CloudKit sync, and safe multi-version database migrations (VersionedSchema & SchemaMigrationPlan). Use when designing data persistence, fixing store corruption, or upgrading app schema between releases.
---

# SwiftData & Core Data Persistence Specialist

This skill provides authoritative guidance on implementing, optimizing, and migrating data persistence using **SwiftData** and **Core Data**, based on Apple's official documentation and WWDC architectural standards.

---

## 1. Schema Design Standards (`@Model`)

### A. Model Definition Rules
1. **Always provide default values:** If CloudKit sync is enabled, every property must either be optional or have an explicit default value.
2. **Define explicit delete rules:** Never leave `@Relationship` delete rules implicit. Always choose `.cascade`, `.nullify`, or `.deny`.
3. **Use `@Transient` for computed or runtime-only state:** Properties marked `@Transient` are never written to SQLite disk.

```swift
import SwiftData
import Foundation

@Model
public final class Project {
    public var id: UUID = UUID()
    public var title: String = ""
    public var createdAt: Date = Date.now
    public var isArchived: Bool = false

    // Explicit relationship with delete rule
    @Relationship(deleteRule: .cascade, inverse: \TaskItem.project)
    public var tasks: [TaskItem] = []

    // Transient property: Not saved to SQLite
    @Transient
    public var isSelectedForBatchAction: Bool = false

    public init(title: String) {
        self.title = title
    }
}
```

---

## 2. Safe Schema Migrations (`VersionedSchema` & `SchemaMigrationPlan`)

When updating an application from Version 1 to Version 2, unversioned schema modifications can cause **fatal startup crashes** (`Store could not be loaded`). Always define explicit `VersionedSchema` namespaces:

### Step 1: Define Schemas per Version
```swift
// Version 1 Schema
public enum AppSchemaV1: VersionedSchema {
    public static var versionIdentifier: Schema.Version = Schema.Version(1, 0, 0)
    public static var models: [any PersistentModel.Type] { [Project.self, TaskItem.self] }

    @Model
    public final class Project {
        public var title: String = ""
        public init(title: String) { self.title = title }
    }
}

// Version 2 Schema (Added 'priority' field, renamed 'title' to 'name')
public enum AppSchemaV2: VersionedSchema {
    public static var versionIdentifier: Schema.Version = Schema.Version(2, 0, 0)
    public static var models: [any PersistentModel.Type] { [Project.self, TaskItem.self] }

    @Model
    public final class Project {
        public var name: String = ""
        public var priority: Int = 1
        public init(name: String, priority: Int = 1) {
            self.name = name
            self.priority = priority
        }
    }
}
```

### Step 2: Define Migration Plan
```swift
public enum AppMigrationPlan: SchemaMigrationPlan {
    public static var schemas: [any VersionedSchema.Type] {
        [AppSchemaV1.self, AppSchemaV2.self]
    }

    public static var stages: [MigrationStage] {
        [migrateV1toV2]
    }

    public static let migrateV1toV2 = MigrationStage.custom(
        fromVersion: AppSchemaV1.self,
        toVersion: AppSchemaV2.self,
        willMigrate: { context in
            // Optional pre-migration validation
        },
        didMigrate: { context in
            // Data transformation: populate new 'name' from old 'title'
            let projects = try context.fetch(FetchDescriptor<AppSchemaV2.Project>())
            for project in projects {
                if project.priority == 0 { project.priority = 1 }
            }
            try context.save()
        }
    )
}
```

### Step 3: Initialize ModelContainer with Migration Plan
```swift
let container = try ModelContainer(
    for: AppSchemaV2.Project.self,
    migrationPlan: AppMigrationPlan.self,
    configurations: ModelConfiguration(isStoredInMemoryOnly: false)
)
```

---

## 3. Concurrency with SwiftData (`@ModelActor`)

**CRITICAL RULE:** `ModelContext` is **NOT thread-safe**. Never access or pass a `ModelContext` across different threads or actors.

To perform background imports, bulk syncs, or intensive calculations without freezing the UI, use the **`@ModelActor`** macro:

```swift
import SwiftData

@ModelActor
public actor BackgroundDataImporter {
    public func importRemoteRecords(_ records: [RemoteRecordDTO]) throws {
        // modelContext and modelExecutor are synthesized by @ModelActor
        for record in records {
            let entity = Project(title: record.name)
            modelContext.insert(entity)
        }
        try modelContext.save()
    }
}
```

---

## 4. SwiftData Verification Checklist

- [ ] **CloudKit Ready:** If using iCloud sync, verify no model uses `@Attribute(.unique)` and all fields have default values or are optional.
- [ ] **No Cross-Thread Context Access:** Ensure `@Query` and `modelContext` in views stay on the `@MainActor`. All background mutations must use `@ModelActor`.
- [ ] **Delete Rules Tested:** Verify what happens when a parent entity is deleted (do children cascade delete or nullify?).
- [ ] **Migration Plan Active:** Any change to model fields in an existing app must increment `VersionedSchema` and be tested with an old store database file.

Wersje

W bazie nie ma innych skilli o nazwie swiftdata-persistence-expert.

Migawka bazy z 13.11.2026 · wersja paczki ac1d59baa907 (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100ios-core-data-swiftdata-persistence
    Obsługuje lokalną trwałość danych w iOS, migracje oraz synchronizację CloudKit z użyciem SwiftData i Core Data.
  • 100swiftdata-core-data-migrations
    Projektuje i testuje migracje schematów SwiftData i Core Data bez utraty danych, z wersjami schematu, etapami i ograniczeniami CloudKit.
  • 95swiftdata
    Wdraża i przegląda trwałość danych w SwiftData: klasy @Model, zapytania @Query i #Predicate, ModelContainer, migracje schematów z VersionedSchema i synchronizację CloudKit.
  • 100swiftdata-pro
    Modeluje dane w SwiftData: klasy @Model, zapytania @Query, ModelContainer, migracje i synchronizację CloudKit na iOS 17+.
  • 100swiftdata-expert-skill
    Pomaga przy schematach SwiftData: relacjach, zapytaniach, konfiguracji kontenera, synchronizacji CloudKit, migracjach i przejściu z Core Data.
  • 100axiom-data
    Pomaga w trwałości danych w aplikacjach Apple: SwiftData, Core Data, GRDB, SQLite, Realm, synchronizacja CloudKit, przechowywanie plików, Codable i migracje.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.