创建一个通用的Swift函数来返回一组Core数据实体 [英] Create a generic Swift function to return an array of Core Data entities

查看:134
本文介绍了创建一个通用的Swift函数来返回一组Core数据实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我对Swift和Core Data都很新颖



我的代码中有几个函数返回一个特定实体类型的数组:

p>

  func fetchStores() - > [商店]? {
var商店:[商店]?
让fetchRequest:NSFetchRequest< Store> = Store.fetchRequest()

do {
stores = try ad.persistentContainer.viewContext.fetch(fetchRequest)
} catch {
assert(false,error。 localizedDescription)
}

返回商店
}

我想创建一个处理所有实体的泛型函数:

  func fetchEntities< T:NSManagedObject>(entity :T)→> [T]? {
var results:[T]?

如果让fetchRequest:NSFetchRequest< T> = T.fetchRequest()为? NSFetchRequest< T> {
do {
results = try ad.persistentContainer.viewContext.fetch(fetchRequest)
} catch {
assert(false,error.localizedDescription)
}
$ else $ {
assert(false,Error:cast to NSFetchRequest< T> failed)
}

返回结果
}

//用法:
let store = Store()
let stores = fetchEntities(entity:store)

有没有办法让我在没有的情况下创建 Store 实例?



TIA

解决方案

你几乎在那里。您只需将参数
类型从 T 更改为 T.Type

  func fetchEntities< T:NSManagedObject>(entity:T.Type) - > [T]? 

,这样您就可以传递一个类型而不是实例:

  let stores = fetchEntities(entity:Store.self)


Caveat: I am still pretty new to both Swift and Core Data

I have several functions in my code that return an array of a specific entity type:

func fetchStores() -> [Store]? {
  var stores: [Store]?
  let fetchRequest: NSFetchRequest<Store> = Store.fetchRequest()

  do {
    stores = try ad.persistentContainer.viewContext.fetch(fetchRequest)
  } catch {
    assert(false, error.localizedDescription)
  }

  return stores
}

I'd like to create a generic function that handles all of my entities:

func fetchEntities<T: NSManagedObject>(entity: T) -> [T]? {
  var results: [T]?

  if let fetchRequest: NSFetchRequest<T> = T.fetchRequest() as? NSFetchRequest<T> {
    do {
      results = try ad.persistentContainer.viewContext.fetch(fetchRequest)
    } catch  {
      assert(false, error.localizedDescription)
    }
  } else {
    assert(false,"Error: cast to NSFetchRequest<T> failed")
  }

  return results
}

// Usage:
let store = Store()
let stores = fetchEntities(entity: store)

Is there a way for me to do this without having to create a Store instance?

TIA

解决方案

You were almost there. You only have to change the parameter type from T to T.Type:

func fetchEntities<T: NSManagedObject>(entity: T.Type) -> [T]?

so that you can pass a type instead of an instance:

let stores = fetchEntities(entity: Store.self)

这篇关于创建一个通用的Swift函数来返回一组Core数据实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆