Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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)
like image 396
Nick Avatar asked Nov 24 '16 22:11

Nick


1 Answers

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.

like image 104
Hamish Avatar answered Nov 06 '22 12:11

Hamish