TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Can somebody tell me what I'm doing wrong here? (SwiftData Predicate)

Forums > SwiftUI

I'm trying to do what is shown here How to dynamically change a query's sort order or predicate

But I am trying to allow both the sort and filter to be dynamic, instead of just the sort. There aren't any examples of how to actually make the predicate dynamic on that page.

import SwiftData
import SwiftUI

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

    @Query(filter: #Predicate<Meal> { meal in true }, sort: [SortDescriptor(\Meal.name)])
    var meals: [Meal]

    var body: some View {
        List {
            ForEach(meals) { meal in
                NavigationLink(value: meal) {
                    MealView(meal: meal)
                }
            }
            .onDelete(perform: deleteMeals)
        }
        .padding(0)
    }

    init(filter: Predicate<Meal>, sort: [SortDescriptor<Meal>], searchText: String) {
        _meals = @Query(filter: filter, sort: sort)
    }

    func deleteMeals(indexSet: IndexSet) {
        for index in indexSet {
            let deletableMeal = meals[index]
            modelContext.delete(deletableMeal)
        }
    }
}

I think I must be setting the type of the filter parameter in the initializer incorrectly, but I don't know what I'm supposed to be setting it to. Does anyboy know?

I'm getting this error:

Cannot assign value of type '_.Type' to type 'Query<Array<Meal>.Element, [Meal]>' (aka 'Query<Meal, Array<Meal>>')

2      

Nevermind... I just wasn't supposed to be putting the @Query inside my initializer, and should have just used Query instead.

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.