swiftxcodecore-dataswiftuifetchrequest

Sorting @FetchRequest (not dynamically) with SwiftUI


I tried the entire day to find the simplest solution to sort a @FetchRequest without any success!

I have tried this little modification:

@AppStorage("sortTitle") private var sortTitle = true

@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(sortDescriptors: [ sortTitle ? SortDescriptor(\.title) : SortDescriptor(\.date) ]) private var items: FetchedResults<Item>

And of course it doesn't work. Actually, I'm looking for something very simple because this isn't a dynamic sorting ; it's more like a one-time sorting that can be done by toggling sortTitle from the Settings screen.

There's of course one online solution (on the link below) but I'm not good enough to understand it correctly at the moment! https://www.youtube.com/watch?v=O4043RVjCGU

Thanks, in advance, for your feedback. :)


Solution

  • You could try this generic fetching View that takes a computed FetchRequest and returns the results, e.g.

    
    var sortDescriptors: [SortDescriptor<Item>] {
        sortTitle ? [SortDescriptor(\.title)] : [SortDescriptor(\.date)]
    }
    
    var body: some View {
        FetchedResultsView(request: FetchRequest(sortDescriptors:) { results in
             ForEach(results) { result in
                ...
            }
        }
    }
    
    struct FetchedResultsView<Content, Result>: View where Content: View, Result: NSFetchRequestResult {
        @FetchRequest var results: FetchedResults<Result>
        let content: ((FetchedResults<Result>) -> Content)
        
        init(request: FetchRequest<Result>, @ViewBuilder content: @escaping (FetchedResults<Result>) -> Content) {
            self._results = request
            self.content = content
        }
        
        var body: some View {
            content(results)
        }
    }