How to write an extension for NSFetchedResultsController in Swift 4

前端 未结 3 1318
有刺的猬
有刺的猬 2021-01-12 05:45

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:

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-12 06:11

    Subclass-ing is not good, composition is a better way to go. Here is my take on this:

    public protocol FetchedDataProtocol {
        associatedtype T: NSFetchRequestResult
        var controller: NSFetchedResultsController { get }
        subscript(_ indexPath: IndexPath) -> T { get }
    }
    

    Doing it this way you avoid casting and mapping:

    public extension FetchedDataProtocol {
        subscript(_ indexPath: IndexPath) -> T {
            return controller.object(at: indexPath)
        }
    }
    

    And then you use it as your own class that has subscript (and whatever you want):

    public struct MainFetchedData: FetchedDataProtocol {
        public let controller: NSFetchedResultsController
        public init(_ controller: NSFetchedResultsController) {
            self.controller = controller
        }
    }
    

提交回复
热议问题