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

Solved: day 58 Dynamically filtering @FetchRequest

Forums > 100 Days of SwiftUI

Hi, I've encountered a problem on day 58 in the want to go further part to apply NSPredicates to a generic FetchRequest type.

I followed all the instruction on the page, and comes back with errors attached to the code under //

struct FilteredList<T: NSManagedObject, Content: View>: View { //Use of undeclared type 'NSManagedObject'
    var fetchRequest: FetchRequest<T> //Type 'T' does not conform to protocol 'NSFetchRequestResult'
    var singers: FetchedResults<T> { fetchRequest.wrappedValue } //Type 'T' does not conform to protocol 'NSFetchRequestResult'

    // this is our content closure; we'll call this once for each item in the list
    let content: (T) -> Content

    var body: some View {
        List(fetchRequest.wrappedValue, id: \.self) { singer in
            self.content(singer)
        }
    }

    init(filterKey: String, filterValue: String, @ViewBuilder content: @escaping (T) -> Content) {
        fetchRequest = FetchRequest<T>(entity: T.entity(), sortDescriptors: [], predicate: NSPredicate(format: "%K BEGINSWITH %@", filterKey, filterValue)) //Type 'T' does not conform to protocol 'NSFetchRequestResult'
        self.content = content
    }
}

Can anyone help? I tried to change the T: NSManagedObject to

  • NSObjectProtocol and NSObject (the error Type 'T' does not conform to protocol 'NSFetchRequestResult still remain on the 3 lines)
  • NSFetchRequestResult (this needs another type constrain on top of the T, I thought it'd be too complicated to try this route)
  • NSManagedObjectID (giving the same error of 'Use of undeclared type 'NSManagedObjectID')

Thank you!

3      

hi,

did you import CoreData for this code? the code otherwise looks fine. you'll see this in the video, but the written transcript seems to have omitted the instruction to do this.

hope that helps,

DMG

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.