UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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!

2      

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.

2      

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)
}

4      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.