core-dataswiftdata

SwiftData - fetch all entities


In CoreData, I use the following code to fetch all entities with a name:

func fetchAllEntities(for entityName: String) -> [NSManagedObject]? {
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)

    do {
        let objects = try container.viewContext.fetch(fetchRequest)
        return objects
    } catch let error as NSError {
        debugPrint("Could not fetch. \(error), \(error.userInfo)")
    }

    return nil
}

And call that like this:

if let allEntries = fetchAllEntities(for: "Entry") as? [Entry] {...}
if let allBooks = fetchAllEntities(for: "Book") as? [Book] {...}

How do I translate that to SwiftData ?


Solution

  • SwiftData is much safer so it allows generics instead of strings

    func fetchAllEntities<SD>() throws -> [SD] where SD : PersistentModel {
        let descriptor: FetchDescriptor = FetchDescriptor<SD>()
        let objects = try container.mainContext.fetch(descriptor)
        return objects
    }
    

    You can then use

    let items: [Item] = fetchAllEntities()
    

    You can do the same thing with CoreData and avoid all of that unwrapping that is prone to typos.

    func fetchAllEntities<MO>() -> [MO]? where MO : NSManagedObject {
        let fetchRequest = NSFetchRequest<MO>()
    
        do {
            let objects = try container.viewContext.fetch(fetchRequest)
            return objects
        } catch let error as NSError {
            debugPrint("Could not fetch. \(error), \(error.userInfo)")
            return nil
        }
    }