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. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 4 lessons in total.
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.
Learn Swift with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 122
- Lessons
- 409
Frequently Asked Questions
Is the “Relationships and Fetch Descriptors” lesson free?
Yes — any 3 lessons of the Swift Academy learning path, including “Relationships and Fetch Descriptors”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
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