简体   繁体   English

在 Swift 5 中转换为泛型类型

[英]Cast to generic type in Swift 5

I'd like to write a generic function, that fetches some kind of data locally, using the Core Data framework.我想编写一个通用的 function,它使用核心数据框架在本地获取某种数据。 I wrote the function like this:我这样写了 function:

func fetch<T:NSManagedObject>(type: T.Type = T.self, completion: @escaping (([T]?) -> ())) {
    do {
        let data = try context.fetch(T.fetchRequest()) as [T]
        completion(data)
    } catch {
        completion(nil)
    }
}

However, the complier tells me this error "Cannot convert value of type '[Any]' to type '[T]' in coercion, arguments to generic parameter 'Element' ('Any' and 'T') are expected to be equal"但是,编译器告诉我这个错误“无法将类型'[Any]'的值转换为强制类型'[T]',arguments 到泛型参数'Element'('Any'和'T')预计相等"

Is there the possibility to do this kind of cast?有没有可能做这种演员?

Try the following code:试试下面的代码:

func fetch<T:NSManagedObject>(type: T.Type = T.self, completion: @escaping (([T]?) -> ())) {
    do {
        let data = try context.fetch(T.fetchRequest()) as? [T]
        completion(data)
    } catch {
        completion(nil)
    }
}

(As Sweeper has pointed out fetch returns an array, so you have to cast the result to [T] and not just T ) (正如 Sweeper 指出的fetch返回一个数组,因此您必须将结果转换为[T]而不仅仅是T

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

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