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

Day 59 - Generic FilteredList in Core Data

Forums > 100 Days of SwiftUI

Hello,

To retrieve information from Core Data we have to create fetch requests. In this project we have made a generic fetch request in the FilteredList struct as shown below

  init(filterKey: String, filterValue: String, sortDescriptor: NSSortDescriptor, @ViewBuilder content: @escaping (T) -> Content) {
    fetchRequest = FetchRequest<T>(entity: T.entity(), sortDescriptors: [sortDescriptor], predicate: NSPredicate(format: "%K BEGINSWITH %@", filterKey, filterValue))
    self.sortDescriptor = sortDescriptor
    self.content = content
  }

In my project I have 3 entities: Candy, Country, and Singer.

In the main view I call this struct in order to display a list of Singers. But I am not sure how Core Data knows that I want Singers (as opposed to Candies or Countries). It is either due to the key path or argument label provided to the closure. Originally I thought both of these served different roles, but after inspection it feels like it must be one of them.

FilteredList(filterKey: "lastName", filterValue: lastNameFilter, sortDescriptor: NSSortDescriptor(keyPath: \Singer.firstName, ascending: true)) { (singer: Singer) in
              Text("\(singer.wrappedFirstName) \(singer.wrappedLastName)")
          }

Can someone shed some light on this?

2      

It knows because of the closure you pass as the content parameter. That closure is of type (T) -> Content, with T and Content being generic placeholders. It's the placeholder T that tells Core Data which entity you want.

So since in this example the parameter to the content closure is (singer: Singer), that means T is a Singer. Core Data then can use that when you build the FetchRequest:

FetchRequest<T>(entity: T.entity(), sortDescriptors: [], predicate: NSPredicate(format: "%K BEGINSWITH %@", filterKey, filterValue))

Which in this example becomes:

FetchRequest<Singer>(entity: Singer.entity(), sortDescriptors: [], predicate: NSPredicate(format: "%K BEGINSWITH %@", filterKey, filterValue))

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.