title: How to write a simple generic Core Data function for all Entities
body: <p><strong>EDIT</strong>: Specifically using Swift Generics</p>
  
  <p>I want a countAll() function for all of my entities and I'm hoping to achieve this by writing one generic function.</p>
  
  <p>The following handles an entity called 'Event', but I want to handle an entity named 'T'.</p>
  
  <p>I'm not sure how to write a generic function like this. Could someone help please? </p>
  
  <pre><code>func countAll() -&gt; Int {
      let request: NSFetchRequest&lt;Event&gt; = Event.fetchRequest()
      do {
        return try persistentContainer.viewContext.count(for: request)
      } catch {
        XCTAssert(false, "Core Data failed to fetch with error: " + error.localizedDescription)
        return 0
      }
  }
  </code></pre>
  
  <p>This is the closest I can get before I hit an error:</p>
  
  <pre><code>func count&lt;T: NSFetchRequestResult&gt;(entityName: String) -&gt; Int {
      let request = NSFetchRequest&lt;T&gt;(entityName: entityName)
      do {
        return try persistentContainer.viewContext.count(for: request)
      } catch {
        XCTAssert(false, "Core Data failed to fetch with error: " + error.localizedDescription)
        return 0
      }
  }
  </code></pre>