【问题标题】:Extending Swift type with method that requires a generic使用需要泛型的方法扩展 Swift 类型
【发布时间】:2018-07-20 13:18:40
【问题描述】:

我的问题是关于使用需要泛型的方法来扩展类型。

我想扩展IndexPath 并添加一个方法来检查它在给定的NSFetchedResultsController 中是否有效。这是我的扩展:

 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
 }

在我的UICollectionViewController 类中,我声明myFetchedResultsController

private var myFetchedResultsController: NSFetchedResultsController&lt;MyModel&gt;!

MyModelNSManagedObject

但是,当我尝试调用我的新方法时:

indexPath.isValid(in: myFetchedResultsController)

我收到一个错误:

无法转换“NSFetchedResultsController!”类型的值到预期的参数类型'NSFetchedResultsController'。 插入 ' 作为! NSFetchedResultsController

我错过了什么? MyModelNSManagedObject 那为什么要我投呢?

【问题讨论】:

    标签: swift generics extension-methods


    【解决方案1】:

    这比我想象的要快。事实证明,将签名更改为包含 &lt;T: NSManagedObject&gt; 可以修复它:

    func isValid&lt;T: NSManagedObject&gt;(in fetchedResultsController: NSFetchedResultsController&lt;T&gt;) -&gt; Bool

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多