RobertJoseph RobertJoseph - 8 months ago 27
Swift Question

Create a generic Swift function to return an array of Core Data entities

Caveat: I am still pretty new to both Swift and Core Data

I have several functions in my code that return an array of a specific entity type:

func fetchStores() -> [Store]? {
var stores: [Store]?
let fetchRequest: NSFetchRequest<Store> = Store.fetchRequest()

do {
stores = try ad.persistentContainer.viewContext.fetch(fetchRequest)
} catch {
assert(false, error.localizedDescription)
}

return stores
}


I'd like to create a generic function that handles all of my entities:

func fetchEntities<T: NSManagedObject>(entity: T) -> [T]? {
var results: [T]?

if let fetchRequest: NSFetchRequest<T> = T.fetchRequest() as? NSFetchRequest<T> {
do {
results = try ad.persistentContainer.viewContext.fetch(fetchRequest)
} catch {
assert(false, error.localizedDescription)
}
} else {
assert(false,"Error: cast to NSFetchRequest<T> failed")
}

return results
}

// Usage:
let store = Store()
let stores = fetchEntities(entity: store)


Is there a way for me to do this without having to create a
Store
instance?

TIA

Answer Source

You were almost there. You only have to change the parameter type from T to T.Type:

func fetchEntities<T: NSManagedObject>(entity: T.Type) -> [T]?

so that you can pass a type instead of an instance:

let stores = fetchEntities(entity: Store.self)