WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Dynamically filtering @FetchRequest with SwiftUI + Distinct Values

Forums > SwiftUI

Hello,

I succesfully implemented the code under the topic "Dynamically filtering @FetchRequest with SwiftUI", and works greatly.

https://www.hackingwithswift.com/books/ios-swiftui/dynamically-filtering-fetchrequest-with-swiftui

However, I need to return only the Distinct values in the List. I do understand I should add these properties:

fetchRequest.resultType = NSDictionaryResultType;
fetchRequest.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:@"name"]];
fetchRequest.returnsDistinctResults = YES;

But I can't seem to find th syntax on doing that in this _fetchRequest scenario.

It seema purely a syntax question, and any help is appreciated.

Thank you!

   

From my understanding these are properties of NSFetchRequest from CoreData not FetchRequest from SwiftUI. So you can't set these properties because they don't exist.

   

Instead of doing this:

init(filter: String) {
    _fetchRequest = FetchRequest<Singer>(sortDescriptors: [], predicate: NSPredicate(format: "lastName BEGINSWITH %@", filter))
}

You would need to use a different initializer on FetchRequest and pass in a configured NSFetchRequest that has its properties set as you need. Something like this:

//first, an extension on your managed object class
extension Singer {
    static var distinctSingers: NSFetchRequest<Singer> = {
        let request = NSFetchRequest<Singer> = Singer.fetchRequest()
        //set up the properties you need
        request.resultType = .dictionaryResultType
        request.propertiesToFetch = ["name"]
        request.returnsDistinctResults = true
        return request
    }
}

//then, in your View's init:

init(filter: String) {
    let request = Singer.distinctSingers
    //add any other specialization to the request, like sort descriptors or predicates
    request.predicate = NSPredicate(format: "lastName BEGINSWITH %@", filter)
    //and then initialize the property wrapper with the request
    _fetchRequest = FetchRequest<Singer>(fetchRequest: request)
}

1      

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.