简体   繁体   English

转换为 swift 中的通用 class 类型

[英]Cast to a generic class type in swift

My objective is to return the fetched results from the DB to any given type (model).我的目标是将从数据库中获取的结果返回到任何给定类型(模型)。 For some reason I'm getting the error as "Use of undeclared type 'model'".出于某种原因,我收到错误为“使用未声明的类型'模型'”。 What am I missing here?我在这里想念什么? and how to achieve my objective.以及如何实现我的目标。

func fetchData<T>(entity:String, model: T)-> T? {


    let request = NSFetchRequest<NSFetchRequestResult>(entityName:entity)
    request.returnsObjectsAsFaults = false

        do {

            let result = try managedObjectContext.fetch(request)
            if result.count > 0 {

                return result as model // Point that gets the error 

            }

        } catch {

          print("Failed to retrive data")
        }

    return nil

}

You want to use as and not is when casting and the type to cast to is T not model , or rather it is [T] since it is an array so the function declaration needs to be modified as well您想在转换时使用as而不是is并且要转换的类型是T而不是model ,或者更确切地说是[T]因为它是一个数组,所以 function 声明也需要修改

func fetchDsata<T>(entity:String, model: T.Type)-> [T]? {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName:entity)
    request.returnsObjectsAsFaults = false
        do {
            let result = try managedObjectContext.fetch(request)
            if result.count > 0 {
                return result as? [T]
            }
        } catch {
          print("Failed to retrive data")
        }
    return nil
}

There's no need to cast.没必要投。

Based on Joakim's answer I recommend to make the method more generic and also throw to hand over the error to the caller.根据 Joakim 的回答,我建议使该方法更通用,并将throw交给调用者。

Creating the fetch request with the generic type gets rid of the type cast使用泛型创建获取请求摆脱了类型转换

func fetchData<T : NSFetchRequestResult>(entity:String, model: T.Type) throws -> [T] {
    let request = NSFetchRequest<T>(entityName:entity)
    request.returnsObjectsAsFaults = false
    return try managedObjectContext.fetch(request)
}

And use it并使用它

do {
    let result = try fetchData(entity: “Foo”, model: Foo.self) 
    print(result)
} catch {
    print("Failed to retrive data")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM