如何转换为通用数组?

时间:2015-01-04 13:43:01

标签: swift

我正在尝试编写通用功能来使用核心数据加载对象列表,我传递实体名称和数组类型。在转换为通用数组时,应用程序崩溃...

func load<T>(#entityName:String, type:T.Type) -> T {
    let fetchRequest = NSFetchRequest()
    let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: appDelegate.managedObjectContext!)
    fetchRequest.entity = entity

    var error:NSError?
    let obj = appDelegate.managedObjectContext?.executeFetchRequest(fetchRequest, error: &error) as T

    return obj
}

我称之为:

self.load(entityName: "CDSection", type: [CDSection].self)

请注意,如果没有通用功能,它可以工作:

let obj = appDelegate.managedObjectContext?.executeFetchRequest(fetchRequest, error: &error) as [CDSection]

作为一个测试,我尝试只传递元素的类型,而不是数组,并返回一个包含此类型元素的数组...这个工作,但我想通过数组类型,在这种情况下我也可以加载不是数组的东西。

func load<T:AnyObject>(#entityName:String, type:T.Type) -> [T] {
    let fetchRequest = NSFetchRequest()
    let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: appDelegate.managedObjectContext!)
    fetchRequest.entity = entity

    var error:NSError?
    let obj = appDelegate.managedObjectContext?.executeFetchRequest(fetchRequest, error: &error) as [T]

    return obj
}

并称之为:

self.load(entityName: "CDSection", type: CDSection.self)

然后我进行了一些实验,但没有成功,例如......

func load<T:[AnyObject]>(#entityName:String, type:T.Type) -> T {
    let fetchRequest = NSFetchRequest()
    let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: appDelegate.managedObjectContext!)
    fetchRequest.entity = entity

    var error:NSError?
    let obj = appDelegate.managedObjectContext?.executeFetchRequest(fetchRequest, error: &error) as T

    return obj
}

我在第一行得到“预期类型名称或协议组成限制'T'”,因为,显然[AnyObject]不是T的有效限制......?

我如何实现我想要的?提前谢谢!

0 个答案:

没有答案