TechnologiesSwiftUI

FetchRequest struct

iOSmacOStvOSwatchOSvisionOSiOS 13.0+✓ renders

A property wrapper type that retrieves entities from a Core Data persistent

How it works

FetchRequest is a property wrapper that retrieves Core Data managed objects and keeps them in sync with a view's body. You declare what to fetch — the entity, an optional predicate, and a sort order — and SwiftUI executes the fetch against the environment's managed object context, then re-runs the request and invalidates the view whenever the underlying store changes. Reach for it when a view needs to display persisted Core Data records directly, without manually loading results or wiring up change notifications.

  1. Declare the fetch with the @FetchRequest wrapper

    Applying the wrapper to a stored property tells SwiftUI to perform a fetch and bind the live results to that property for the lifetime of the view. Here @FetchRequest wraps the private property items, so the view always reflects the current contents of the store for that request.

  2. Order the results with sortDescriptors

    The sortDescriptors: parameter takes an array of SortDescriptor values that determine the order of the returned objects; pass an empty array for no defined order. The example sorts by the timestamp key path with order: .reverse, so the most recent records appear first.

  3. Read the live results through FetchedResults

    The wrapped value is a FetchedResults collection — a random-access view over the fetched managed objects that updates in place as the store changes. The view binds it as items: FetchedResults<Item> and reads from it like any Swift collection, including items.count for the section header.

  4. Drive view content from the fetched objects

    Because FetchedResults is a collection of identifiable managed objects, it plugs straight into list-building views that iterate and rebuild when results change. ForEach(items) walks each item, and the rows read managed-object properties such as item.name directly.

Try it — Change order: .reverse to order: .forward in the sortDescriptors: array and watch the rows in the list reorder from oldest to newest.

Example & preview

Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.

FetchRequest.swift
struct FetchRequestDemo: View {
    @FetchRequest(
        sortDescriptors: [SortDescriptor(\.timestamp, order: .reverse)]
    ) private var items: FetchedResults<Item>

    var body: some View {
        List {
            Section("Recent Items (\(items.count))") {
                ForEach(items) { item in
                    Label(item.name, systemImage: "clock")
                }
            }
        }
        .padding()
    }
}
Live preview
Recent Items ({items.count})
Recent Items ({items.count})
swift → lexer → parser → sema → uiir → canvas Open in Studio ↗
What's new in SwiftUI 27 →