The @FetchRequest property wrapper in SwiftUI
Learn how to request data from the Core Data store in a SwiftUI view
updated on 19 Sep 2022 · 2 min read
A @FetchRequest property wrapper provided by SwiftUI allows us to fetch data from a Core Data store in a SwiftUI view.
A basic fetch request to fetch a list of Item entities looks likes this:
@FetchRequest(sortDescriptors: [])private var items: FetchedResults<Item>

The @FetchRequest above is applied to the items property of type FetchedResults<Item>. FetchedResults is a collection type, so we can use it in a List the same way as an array.
List {ForEach(items) { item inText("Item \(item.name ?? "")")}}
To filter or sort the results, FetchRequest offers sortDescriptors and predicate as parameters.
@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Item.date, ascending: true)],predicate: NSPredicate(format: "name BEGINSWITH %@", "t"))private var items: FetchedResults<Item>
The fetch request above will deliver items that start with the letter t and are sorted by their date attribute.
Note: The fetch request and its results use the managed object context stored in the environment. For that reason, we need to inject a Core Data managed object context into the environment before using it. Check out this guide on using Core Data with SwiftUI to learn more.

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