Here's how to dynamically set the predicates for your fetch request. First, the properties I have in my SwiftUI view:
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Pokemon.id, ascending: true)],
animation: .default
) private var pokedex: FetchedResults<Pokemon>
@State var searchText = ""
@State var filterByFavorites = false
var compoundPredicate: NSPredicate {
var predicates: [NSPredicate] = []
// Add search predicate
if !searchText.isEmpty {
predicates.append(NSPredicate(format: "name contains[c] %@", searchText))
}
// Add favorite filter predicate
if filterByFavorites {
predicates.append(NSPredicate(format: "favorite == %d", true))
}
// Combine predicates
return NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
}
Notice I don't set any predicate in the fetch request at this point. Also notice, the part that makes this all work is the compoundPredicate computed property. I start with an empty predicates array, then I check my searchText and append the appropriate predicate if the condition is true. Then I check my filterByFavorites property and do the same.
Alright, now the code inside the body var that makes it work. I won't post my whole view since most of it is irrelevant, but here is where I add my List view which shows my pokedex fetched results:
List(pokedex.filter { compoundPredicate.evaluate(with: $0) }) { pokemon in
I filter my pokedex fetched results with the compoundPredicate and evaluate every single pokemon in the list to make sure only those that match the criteria are shown.
I also have a .searchable(text: $searchText, prompt: "Find a Pokemon") modifier on the List view to manage the searching part. And then I have a button the user can tap to toggle filterByFavorites between true and false.
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: