Understanding the @FetchRequest property wrapper in SwiftUI
Learn how to request data from the Core Data store in a SwiftUI view.
19 Aug 2024 · 2 min read
The @FetchRequest property wrapper in SwiftUI simplifies the process of fetching data from a Core Data store for use in a SwiftUI view.
Let's dive in and see how it works.

Basic fetch request
A basic fetch request to fetch a list of Item entities looks as follows:
@FetchRequest(sortDescriptors: [])private var items: FetchedResults<Item>
The @FetchRequest above is applied to the items property of type FetchedResults<Item>. Since FetchedResults conforms to the Collection protocol, we can use it just like an array in a List:
List {ForEach(items) { item inText("Item \(item.name)")}}
Filtering and sorting with FetchRequest
The FetchRequest initializer also supports filtering and sorting through its sortDescriptors and predicate parameters. Here’s how we can use them:
@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Item.date, ascending: true)],predicate: NSPredicate(format: "name BEGINSWITH %@", "t"))private var items: FetchedResults<Item>
This fetch request filters the results to include only items whose names begin with the letter "t" and sorts them by the date attribute in ascending order.
Important Considerations
It’s important to note that both the fetch request and its results rely on the managed object context provided in the environment. Therefore, we must inject a Core Data managed object context into the environment before using @FetchRequest. To learn more about setting up Core Data in SwiftUI, check out our comprehensive guide on integrating Core Data with SwiftUI.



Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips



