【问题标题】:swift extension func with generic type - isEmpty for FetchedResults具有泛型类型的快速扩展 func - FetchedResults 的 isEmpty
【发布时间】:2018-04-16 01:12:36
【问题描述】:

我在实现扩展函数以确定实体是否包含任何结果时遇到了一些麻烦。最终目标是确定一个实体是否有结果,如果没有,则在应用启动时将其播种(对于某些实体,例如国家/地区列表等...)

这是我能够得到的地方,但是 swift 编译器并不满意;错误:类型“T”不符合协议“NSFetchRequestResult”

extension NSManagedObject {
    func isEmpty<T>(context: NSManagedObjectContext, entityName: String, entityType: T.Type) -> Bool {
        do {
            let fetch = NSFetchRequest<T>(entityName: entityName)
            let count = try context.fetch(fetch)
            return count == 0 ? true : false
        } catch {
            return true
        }
    }
}

【问题讨论】:

    标签: swift generics


    【解决方案1】:

    您必须将 T 限制为 NSManagedObject 子类。 如果您只对 对象数:

    func isEmpty<T: NSManagedObject>(context: NSManagedObjectContext, entityName: String, entityType: T.Type) -> Bool {
        do {
            let fetch = NSFetchRequest<T>(entityName: entityName)
            let count = try context.count(for: fetch)
            return count == 0
        } catch {
            return true
        }
    }
    

    但实际上你不需要那个参数:

    func isEmpty(context: NSManagedObjectContext, entityName: String) -> Bool {
        do {
            let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
            let count = try context.count(for: fetch)
            return count == 0
        } catch {
            return true
        }
    }
    

    作为性能改进,您还可以设置

            fetch.fetchLimit = 1
    

    备注:声明

    return someBooleanCondition ? true : false
    

    可以(并且应该)总是简化为

    return someBooleanCondition
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多