如何将提取结果<Obj>从@FetchRequest转换为 [Obj]?



如何在Swift中将FetchedResults<Obj>强制转换为[Obj]

@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: Obj.name, ascending: false)]
) private var objects: FetchedResults<Obj>

我做了以下事情:

objects as? [Obj] ?? []

但这给了我一个错误:

Cast from 'FetchedResults<Obj>' to unrelated type '[Obj]' always fails

正如错误所指出的,不能在不相关的类型之间进行as?强制转换,FetchedResults与Array无关。如果你需要一个数组,你可以从任何序列(如FetchedResults(创建它,使用数组的初始值设定项:

let arrayObjects = Array(objects)

最新更新