Every time I try to compile this, I get the error:
Cannot convert value of type '[T]' to expected argument type '[_]'
I'm not really sure why this keeps happening, and I've tried to look up solutions but have found nothing that seemed helpful. Here's 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 the error on this line:
return FetchResult(true, results as! [T], nil)
The problem is that you have two generic placeholder types called T
. One at class scope, one at method scope. When you say results as! [T]
, you're referring to the T
at method scope – which is unrelated to the class scope T
used in your FetchResult
type-alias, which is return type of your fetch
method.
Therefore you simply need to rename one of your placeholders, or better yet, 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 simply call fetch(inContext:)
on the FetchRequest
instance that you want to fetch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With