How to write a simple generic Core Data function for all Entities

Viewed 3180

EDIT: Specifically using Swift Generics

I want a countAll() function for all of my entities and I'm hoping to achieve this by writing one generic function.

The following handles an entity called 'Event', but I want to handle an entity named 'T'.

I'm not sure how to write a generic function like this. Could someone help please?

func countAll() -> Int {
    let request: NSFetchRequest<Event> = Event.fetchRequest()
    do {
      return try persistentContainer.viewContext.count(for: request)
    } catch {
      XCTAssert(false, "Core Data failed to fetch with error: " + error.localizedDescription)
      return 0
    }
}

This is the closest I can get before I hit an error:

func count<T: NSFetchRequestResult>(entityName: String) -> Int {
    let request = NSFetchRequest<T>(entityName: entityName)
    do {
      return try persistentContainer.viewContext.count(for: request)
    } catch {
      XCTAssert(false, "Core Data failed to fetch with error: " + error.localizedDescription)
      return 0
    }
}
2 Answers
Related