comeonoliver/skillshub/axiom-swiftdata

Claude Code and agent skill by comeonoliver/skillshub

Trust tier 3
  • community
  • ext:[{"type":"config","description":"Configuration overrides"}]
Source check pending

Checking that the SKILL.md file is still in the repository.

Use when working with SwiftData - @Model definitions, @Query in SwiftUI, @Relationship macros, ModelContext patterns, CloudKit integration, iOS 26+ features, and Swift 6 concurrency with @MainActor — Apple's native persistence framework

Install

npx vskill@latest install comeonoliver/skillshub/axiom-swiftdata

Semi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard

SKILL.md

The same SKILL.md was published earlier as comeonoliver/skillshub/axiom-swiftdata.

SwiftData

Overview

Apple's native persistence framework using @Model classes and declarative queries. Built on Core Data, designed for SwiftUI.

Core principle Reference types (class) + @Model macro + declarative @Query for reactive SwiftUI integration.

Requires iOS 17+, Swift 5.9+ Target iOS 26+ (this skill focuses on latest features) License Proprietary (Apple)

When to Use SwiftData

Choose SwiftData when you need
  • ✅ Native Apple integration with SwiftUI
  • ✅ Simple CRUD operations
  • ✅ Automatic UI updates with @Query
  • ✅ CloudKit sync (iOS 17+)
  • ✅ Reference types (classes) with relationships
Use SQLiteData instead when
  • Need value types (structs)
  • CloudKit record sharing (not just sync)
  • Large datasets (50k+ records) with specific performance needs
Use GRDB when
  • Complex raw SQL required
  • Fine-grained migration control needed

For migrations See the axiom-swiftdata-migration skill for custom schema migrations with VersionedSchema and SchemaMigrationPlan. For migration debugging, see axiom-swiftdata-migration-diag.

Example Prompts

These are real questions developers ask that this skill is designed to answer:

Basic Operations
1. "I have a notes app with folders. I need to filter notes by folder and sort by last modified. How do I set up the @Query?"

→ The skill shows how to use @Query with predicates, sorting, and automatic view updates

2. "When a user deletes a task list, all tasks should auto-delete too. How do I set up the relationship?"

→ The skill explains @Relationship with deleteRule: .cascade and inverse relationships

3. "I have a relationship between User → Messages → Attachments. How do I prevent orphaned data when deleting?"

→ The skill shows cascading deletes, inverse relationships, and safe deletion patterns

CloudKit & Sync
4. "My chat app syncs messages to other devices via CloudKit. Sometimes messages conflict. How do I handle sync conflicts?"

→ The skill covers CloudKit integration, conflict resolution strategies (last-write-wins, custom resolution), and sync patterns

5. "I'm adding CloudKit sync to my app, but I get 'Property must have a default value' error. What's wrong?"

→ The skill explains CloudKit constraints: all properties must be optional or have defaults, explains why (network timing), and shows fixes

6. "I want to show users when their data is syncing to iCloud and what happens when they're offline."

→ The skill shows monitoring sync status with notifications, detecting network connectivity, and offline-aware UI patterns

7. "I need to share a playlist with other users. How do I implement CloudKit record sharing?"

→ The skill covers CloudKit record sharing patterns (iOS 26+) with owner/permission tracking and sharing metadata

Performance & Optimization
8. "I need to query 50,000 messages but only display 20 at a time. How do I paginate efficiently?"

→ The skill covers performance patterns, batch fetching, limiting queries, and preventing memory bloat with chunked imports

9. "My app loads 100 tasks with relationships, and displaying them is slow. I think it's N+1 queries."

→ The skill shows how to identify N+1 problems without prefetching, provides prefetching pattern, and shows 100x performance improvement

10. "I'm importing 1 million records from an API. What's the best way to batch them without running out of memory?"

→ The skill shows chunk-based importing with periodic saves, memory cleanup patterns, and batch operation optimization

11. "Which properties should I add indexes to? I'm worried about over-indexing slowing down writes."

→ The skill explains index optimization patterns: when to index (frequently filtered/sorted properties), when to avoid (rarely used, frequently changing), maintenance costs

Migration from Legacy Frameworks
12. "We're migrating from Realm/Core Data to SwiftData"

→ See the comparison table in Migration section below, then follow realm-to-swiftdata-migration or axiom-swiftdata-migration for detailed guides


@Model Definitions

Basic Model
swift
import SwiftData
@Model
final class Track {
@Attribute(.unique) var id: String
var title: String
var artist: String
var duration: TimeInterval
var genre: String?
init(id: String, title: String, artist: String, duration: TimeInterval, genre: String? = nil) {
self.id = id
self.title = title
self.artist = artist
self.duration = duration
self.genre = genre
}
}
Key patterns
  • Use final class, not struct (omit final if you need subclasses — see Class Inheritance below)
  • Use @Attribute(.unique) for primary key-like behavior
  • Provide explicit init (SwiftData doesn't synthesize)
  • Optional properties (String?) are nullable
  • Use @Attribute(.preserveValueOnDeletion) on properties whose values should survive even after the object is deleted (useful for analytics, audit trails)
Relationships
swift
@Model
final class Track {
@Attribute(.unique) var id: String
var title: String
@Relationship(deleteRule: .cascade, inverse: \Album.tracks)
var album: Album?
init(id: String, title: String, album: Album? = nil) {
self.id = id
self.title = title
self.album = album
}
}
@Model
final class Album {
@Attribute(.unique) var id: String
var title: String
@Relationship(deleteRule: .cascade)
var tracks: [Track] = []
init(id: String, title: String) {
self.id = id
self.title = title
}
}
Many-to-Many Self-Referential Relationships
swift
@MainActor // Required for Swift 6 strict concurrency
@Model
final class User {
@Attribute(.unique) var id: String
var name: String
// Users following this user (inverse relationship)
@Relationship(deleteRule: .nullify, inverse: \User.following)
var followers: [User] = []
// Users this user is following
@Relationship(deleteRule: .nullify)
var following: [User] = []
init(id: String, name: String) {
self.id = id
self.name = name
}
}
CRITICAL: SwiftData automatically manages BOTH sides when you modify ONE side.

✅ Correct — Only modify ONE side

swift
// user1 follows user2 (modifying ONE side)
user1.following.append(user2)
try modelContext.save()
// SwiftData AUTOMATICALLY updates user2.followers
// Don't manually append to both sides - causes duplicates!

❌ Wrong — Don't manually update both sides

swift
user1.following.append(user2)
user2.followers.append(user1) // Redundant! Creates duplicates in CloudKit sync
Unfollowing (remove from ONE side only)
swift
user1.following.removeAll { $0.id == user2.id }
try modelContext.save()
// user2.followers automatically updated
Verifying relationship integrity (for debugging)
swift
// Check if relationship is truly bidirectional
let user1FollowsUser2 = user1.following.contains { $0.id == user2.id }
let user2FollowedByUser1 = user2.followers.contains { $0.id == user1.id }
// These MUST always match after save()
assert(user1FollowsUser2 == user2FollowedByUser1, "Relationship corrupted!")
CloudKit Sync Recovery (if relationships become corrupted)
swift
// If CloudKit sync creates duplicate/orphaned relationships:
// 1. Backup current state
let backup = user.following.map { $0.id }
// 2. Clear relationships
user.following.removeAll()
user.followers.removeAll()
try modelContext.save()
// 3. Rebuild from source of truth (e.g., API)
for followingId in backup {
if let followingUser = fetchUser(id: followingId) {
user.following.append(followingUser)
}
}
try modelContext.save()
// 4. Force CloudKit resync (in ModelConfiguration)
// Re-create ModelContainer to force full sync after corruption recovery
Delete rules
  • .cascade - Delete related objects
  • .nullify - Set relationship to nil
  • .deny - Prevent deletion if relationship exists
  • .noAction - Leave relationship as-is (careful!)

Class Inheritance

SwiftData supports class inheritance for hierarchical models. Use when you have a clear IS-A relationship (e.g., BusinessTrip IS-A Trip) and need both broad queries (all trips) and type-specific queries.

Base and Subclass Pattern

Apply @Model to both base class and subclasses. Omit final on the base class.

swift
@Model class Trip {
@Attribute(.preserveValueOnDeletion)
var name: String
var destination: String
var startDate: Date
var endDate: Date
@Relationship(deleteRule: .cascade, inverse: \Accommodation.trip)
var accommodation: Accommodation?
init(name: String, destination: String, startDate: Date, endDate: Date) {
self.name = name
self.destination = destination
self.startDate = startDate
self.endDate = endDate
}
}
@Model class BusinessTrip: Trip {
var purpose: String
var expenseCode: String
@Relationship(deleteRule: .cascade, inverse: \BusinessMeal.trip)
var businessMeals: [BusinessMeal] = []
init(name: String, destination: String, startDate: Date, endDate: Date,
purpose: String, expenseCode: String) {
self.purpose = purpose
self.expenseCode = expenseCode
super.init(name: name, destination: destination, startDate: startDate, endDate: endDate)
}
}
Type-Based Queries with #Predicate

Query all base class instances (includes subclasses), or filter by type:

swift
// All trips (includes BusinessTrip, PersonalTrip, etc.)
@Query(sort: \Trip.startDate) var allTrips: [Trip]
// Only business trips — use `is` in #Predicate
@Query(filter: #Predicate<Trip> { $0 is BusinessTrip }) var businessTrips: [Trip]
// Filter on subclass-specific properties — use `as?` cast
let vacationPredicate = #Predicate<Trip> {
if let personal = $0 as? PersonalTrip {
return personal.reason == .vacation
}
return false
}
@Query(filter: vacationPredicate) var vacationTrips: [Trip]
Polymorphic Relationships

Relationships typed to the base class can hold mixed subclass instances:

swift
@Model class TravelPlanner {
var name: String
@Relationship(deleteRule: .cascade)
var upcomingTrips: [Trip] = [] // Can contain BusinessTrip and PersonalTrip
init(name: String) { self.name = name }
}

Cast to access subclass-specific properties:

swift
for trip in planner.upcomingTrips {
if let business = trip as? BusinessTrip {
print(business.expenseCode)
}
}
When to Use Inheritance vs Alternatives
SignalUse InheritanceUse Enum/Flag Instead
Subclasses share many base propertiesYes—
Need type-based queries across all modelsYes—
Subclasses have their own relationshipsYes—
Only 1-2 distinguishing properties—Yes
Query only on specialized properties—Yes
Protocol conformance suffices—Yes

Keep hierarchies shallow (1-2 levels). Deep chains complicate schema migrations and queries.

ModelContainer Setup

SwiftUI App
swift
import SwiftUI
import SwiftData
@main
struct MusicApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: [Track.self, Album.self])
}
}
Custom Configuration
swift
let schema = Schema([Track.self, Album.self])
let config = ModelConfiguration(
schema: schema,
url: URL(fileURLWithPath: "/path/to/database.sqlite"),
cloudKitDatabase: .private("iCloud.com.example.app")
)
let container = try ModelContainer(
for: schema,
configurations: config
)
In-Memory (Tests)
swift
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(
for: schema,
configurations: config
)

Queries in SwiftUI

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
5

Not refreshed yet.

Extension points

  • configConfiguration overrides

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/comeonoliver/skillshub/axiom-swiftdata/badge)](https://verified-skill.com/skills/comeonoliver/skillshub/axiom-swiftdata)

Something wrong with this skill or its page? Tell us.