Поскольку FetchedResults<T>
является RandomAccessCollection
, а массив swift также является RandomAccessCollection
, здесь возможное решение.
Протестировано с Xcode 11.4 / iOS 13.4
struct ContentView: View {
@Environment(\.managedObjectContext) var context
@FetchRequest(entity: Person.entity(), sortDescriptors: [])
var result: FetchedResults<Person>
var body: some View {
VStack(alignment: .leading) {
Text("Persons").font(.title)
PersonsView(results: result) // FetchedResults<Person> is a collection
}
}
}
// generalize PersonsView to depend just on collection
struct PersonsView<Results:RandomAccessCollection>: View where Results.Element == Person {
let results: Results
var body: some View {
ForEach(results, id: \.self) { person in
Text("Name: \(person.name ?? "<unknown>")")
}
}
}
struct ChildView_Previews: PreviewProvider {
static var previews: some View {
PersonsView(results: [Person()]) // << use regular array to test
}
}