Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftData query with dynamic properties in a View

I'm trying to figure out how to make a SwiftUI view that displays data from SwiftData using a query that includes variables passed into the view. I'm guessing that I won't be able to use the @Query syntax, but has anyone come up with a workable method to do something like this?

Do I need to abandon the @Query and just create a view model that instantiates it's own ModelContainer and ModelContext?

This code is obviously not compiling because the @Query is referencing the startDate and endDate variables, but this is what I want.

struct MyView: View {
    @Environment(\.modelContext) var modelContext

    @Query(FetchDescriptor<Measurement>(predicate: #Predicate<Measurement> {
    $0.date >= startDate && $0.date <= endDate }, sortBy: [SortDescriptor(\Measurement.date)])) var measurements: [Measurement]

    let startDate: Date = Date.distantPast
    let endDate: Date = Date.distantFuture

    var body: some View {
        Text("Help")
    }
}
like image 246
Mike Bedar Avatar asked Sep 10 '25 22:09

Mike Bedar


1 Answers

You can't have a dynamic query (not yet) but a workaround is to inject in the dates (or the full predicate) into the view and create the query that way.

@Query var measurements: [Measurement]

init(startDate: Date, endDate: Date) {
    let predicate = #Predicate<Measurement> {
        $0.date >= startDate && $0.date <= endDate
    }

    _measurements = Query(filter: predicate, sort: \.date)
}
like image 178
Joakim Danielson Avatar answered Sep 13 '25 13:09

Joakim Danielson