bruno88rick/SwiftDataDynamicallySortAndFilter

new dynamic approach with 17.5

Opened this issue · 0 comments

Hi. with 17.4 they added a 'evaluate' which makes dynamic predicates less challenging.

 public var predicateSearch: Predicate<CRTask> {
        
        var filterFavorites: Predicate<CRTask>
        var filterSearch: Predicate<CRTask>
        var filterTaskType: Predicate<CRTask>
        
        if searchText.isEmpty {
            filterSearch = #Predicate<CRTask> { rec in 1 == 0 }
        } else {
            var text = searchText
            filterSearch = #Predicate<CRTask> { $0.title.localizedStandardContains(text) }
        }
        
        if let taskType = taskType {
            let taskTypeId = taskType.id
            filterTaskType = #Predicate<CRTask> { $0.taskTypeId == taskTypeId }
        } else {
            filterTaskType = #Predicate<CRTask> { rec in 1 == 1 } // show all types
        }
        

        if isFavorite  {
            filterFavorites = #Predicate<CRTask> { $0.Favorited == 1 }
        } else {
            filterFavorites = #Predicate<CRTask> { rec in 1 == 1 }  // show both types
        }
        
        
        var filter: Predicate<CRTask>
        if searchText.isEmpty {
            filter = #Predicate<CRTask> {
                (filterFavorites.evaluate($0)   && filterTaskType.evaluate($0)    )
            }
        } else {
            filter = #Predicate<CRTask> {
                filterSearch.evaluate($0)
            }
            
        }
        
        
        return filter
    }

more info at https://github.com/NoahKamara/CompoundPredicate
HTH