Cannot convert value of type '[T]' to expected type of argument '[_]'

Every time I try to compile this, I get an error message:

Cannot convert value of type '[T]' to expected argument type '[_]' 

I am not sure why this is happening, and I tried to find solutions, but did not find anything useful. Here is my code:

 class FetchRequest <T: NSManagedObject>: NSFetchRequest<NSFetchRequestResult> { init(entity: NSEntityDescription) { super.init() self.entity = entity } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } typealias FetchResult = (success: Bool, objects: [T], error: NSError?) func fetch <T> (request: FetchRequest<T>, context: NSManagedObjectContext) -> FetchResult { do { let results = try context.fetch(request) return FetchResult(true, results as! [T], nil) } catch let error as NSError { return (false, [], error) } } } 

EDIT:

I get an error on this line:

 return FetchResult(true, results as! [T], nil) 
+5
source share
1 answer

The problem is that you have two common types of placeholders called T One in the class, one in the volume of the method. When you say results as! [T] results as! [T] , you are referring to a region T in a method scope that is not associated with a region of class T used in your alias type FetchResult , which is the return type of your fetch method.

Therefore, you just need to rename one of your placeholders or, even better, eliminate the seemingly redundant request: parameter from the method and just use self instead:

 func fetch(inContext context: NSManagedObjectContext) -> FetchResult { do { let results = try context.fetch(self) return (true, results as! [T], nil) } catch let error as NSError { return (false, [], error) } } 

Now you can just call fetch(inContext:) on the instance of FetchRequest that you want to get.

+3
source

Source: https://habr.com/ru/post/1260309/


All Articles