My question is about extending a type with a method that requires a generic.
I want to extend IndexPath
and add a method to check if it's valid in a given NSFetchedResultsController
. Here's my extension:
public extension IndexPath {
func isValid(in fetchedResultsController: NSFetchedResultsController<NSManagedObject>) -> Bool {
guard let sections = fetchedResultsController.sections,
section < sections.count,
item < sections[section].numberOfObjects else {
return false
}
return true
}
In my UICollectionViewController
class, I declare myFetchedResultsController
:
private var myFetchedResultsController: NSFetchedResultsController<MyModel>!
MyModel
is a NSManagedObject
.
However, when I try to call my new method:
indexPath.isValid(in: myFetchedResultsController)
I get an error:
Cannot convert value of type 'NSFetchedResultsController!' to expected argument type 'NSFetchedResultsController'. Insert ' as! NSFetchedResultsController
What am I missing? MyModel
is NSManagedObject
so why is it asking me to cast it?
This was quicker than I thought. It turns out that changing the signature to include <T: NSManagedObject>
fixes it:
func isValid<T: NSManagedObject>(in fetchedResultsController: NSFetchedResultsController<T>) -> Bool
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.