I'm trying to write a simple extension to the NSFetchedResultsController
class in Swift 4.
Here's my first attempt - which worked in Swift 3:
public extension NSFetchedResultsController
{
public func sectionCount() -> Int
{
if self.sections == nil
{
return 0
}
return self.sections!.count
}
}
But I get this compile error in Xcode 9 beta 2 with Swift 4:
Extension of a generic Objective-C class cannot access the class's generic parameters at runtime
I've tried other variations to no avail. Note that I can create an extension bound to a specific type of NSManagedObject
matching the resultType
; but this has the disadvantage that I need to create an extension for every managed object type used with the NSFetchedResultsController
.
The latest Swift 4 docs don't seem to explain this well.
Subclass-ing is not good, composition is a better way to go. Here is my take on this:
Doing it this way you avoid casting and mapping:
And then you use it as your own class that has subscript (and whatever you want):
We ended up with subclass (Swift 4). Idea behind - pass type as argument. Rest of setup operates
NSManagedObject
type in order to work around compile errors.Extensions:
Usage:
I think I found the answer to this one. The function needs to be available to Objective-C.
Adding
@objc
to thefunc
should remove the compile error. At least it did for me!