How to Apply the Type to a Nsfetchrequest Instance

How to apply the type to a NSFetchRequest instance?

let request: NSFetchRequest<NSFetchRequestResult> = Level.fetchRequest()


let request: NSFetchRequest<Level> = Level.fetchRequest()

depending which version you want.

You have to specify the generic type because otherwise the method call is ambiguous.

The first version is defined for NSManagedObject, the second version is generated automatically for every object using an extension, e.g:

extension Level {
@nonobjc class func fetchRequest() -> NSFetchRequest<Level> {
return NSFetchRequest<Level>(entityName: "Level");

@NSManaged var timeStamp: NSDate?

The whole point is to remove the usage of String constants.

Swift3: Passing parameters into NSFetchRequest method

I haven't tried this but I think something like this would work...

func findCoreDataObjects<T: NSManagedObject>() -> [T] {
let request = T.fetchRequest
let searchResults = try context.fetch(request)
... use(searchResults) ...
print("Error with request: \(error)")

You have to make the entire function generic and so you have to tell it what type T is when calling it.


I think that should do the job. Not entirely certain though as I'm new to generics myself :D

Cannot convert value of type 'NSFetchRequestNSFetchRequestResult' to specified type 'NSFetchRequestT'

T.fetchRequest() returns a NSFetchRequest<NSFetchRequestResult>,
you have to explicitly cast it to the specific NSFetchRequest<T>:

let fetchRequest = T.fetchRequest() as! NSFetchRequest<T>
let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { result in
success(result.finalResult ?? [])

Error casting NSFetchRequestT to NSFetchRequestNSFetchRequestResult where T is generic NSManagedObject

You have to cast the type because the generic type of NSFetchRequest – which is constrained to NSFetchRequestResult – can also be NSDictionary or NSNumber or NSManagedObjectID.

Rather than making a generic type more generic I recommend to use a protocol with associated types like described here

Related Topics

Leave a reply