Relationships and Fetch Descriptors
Modelling one-to-many relationships and querying with FetchDescriptor.
Relationships and Fetch Descriptors is a free Swift Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
SwiftData Relationships
Declare relationships between @Model classes using Swift properties. SwiftData infers the relationship type.
@Model
class Author {
var name: String
@Relationship(deleteRule: .cascade) var books: [Book] = []
init(name: String) { self.name = name }
}@Relationship Attribute
Use @Relationship to specify delete rules and inverse relationships explicitly.
@Model
class Book {
var title: String
var author: Author?
init(title: String) { self.title = title }
}Delete Rules
Delete rules control what happens to related objects when the parent is deleted: .nullify, .cascade, .deny.
// .cascade: deleting Author deletes all Books
// .nullify: deleting Author sets book.author to nil
// .deny: prevents deletion if related objects exist
@Relationship(deleteRule: .cascade) var books: [Book] = []One-to-Many Relationship
A one-to-many relationship is declared as an array property on the "one" side.
@Model class Department {
var name: String
@Relationship(deleteRule: .cascade) var employees: [Employee] = []
init(name: String) { self.name = name }
}
@Model class Employee {
var name: String
var department: Department?
init(name: String) { self.name = name }
}Many-to-Many Relationships
Declare arrays on both sides for a many-to-many relationship.
@Model class Student {
var name: String
var courses: [Course] = []
init(name: String) { self.name = name }
}
@Model class Course {
var title: String
var students: [Student] = []
init(title: String) { self.title = title }
}FetchDescriptor
FetchDescriptor replaces NSFetchRequest in SwiftData. Configure it with predicate, sort, and fetch limit.
var descriptor = FetchDescriptor<Book>(
predicate: #Predicate { $0.title.contains("Swift") },
sortBy: [SortDescriptor(\Book.title)]
)
descriptor.fetchLimit = 10
let books = try context.fetch(descriptor)Sorting with SortDescriptor
Pass an array of SortDescriptor to FetchDescriptor for multi-column sorting.
let descriptor = FetchDescriptor<Item>(
sortBy: [
SortDescriptor(\Item.priority, order: .reverse),
SortDescriptor(\Item.name)
]
)Counting Without Fetching
Use context.fetchCount to count matching records without loading all objects into memory.
let descriptor = FetchDescriptor<Book>(
predicate: #Predicate { $0.rating > 4 }
)
let count = try context.fetchCount(descriptor)
print("High-rated books: \(count)")Prefetching Relationships
Set relationshipKeyPathsForPrefetching on a FetchDescriptor to eagerly load related objects.
var descriptor = FetchDescriptor<Author>()
descriptor.relationshipKeyPathsForPrefetching = [\Author.books]
let authors = try context.fetch(descriptor)@Query with FetchDescriptor-like Options
The @Query macro supports the same sorting and predicate options as FetchDescriptor.
@Query(
filter: #Predicate<Book> { $0.author?.name == "Apple" },
sort: \Book.title
)
var books: [Book]Batch Operations
SwiftData supports batch deletes via context.delete(model:where:) for efficient bulk operations.
try context.delete(model: Book.self, where: #Predicate { $0.rating < 2 })Quick Check
Which SwiftData type replaces NSFetchRequest for fetching @Model objects with filters and sorting?
Lesson Recap
Declare relationships with @Relationship(deleteRule:) on @Model classes. Use FetchDescriptor with #Predicate and SortDescriptor to query data. Use fetchCount for counting and batch delete for bulk removal.
Frequently asked questions
Is the “Relationships and Fetch Descriptors” lesson free?
Yes — the full text of “Relationships and Fetch Descriptors” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “Relationships and Fetch Descriptors”?
Modelling one-to-many relationships and querying with FetchDescriptor. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Relationships and Fetch Descriptors” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Core Data Stack: NSPersistentContainer Setup
- SwiftData @Model and ModelContext
- Relationships and Fetch Descriptors
- Lightweight Migrations and CloudKit Sync