Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
EntityIterator: Wrapper around SwiftUI's ForEach to iterate through Core Data entities according to a predicate and sort descriptors you can change at runtime
//adapted via:
import SwiftUI
import CoreData
struct EntityIterator<Entity: NSManagedObject, Content: View>: View {
var fetchRequest: FetchRequest<Entity>
var results: FetchedResults<Entity> { fetchRequest.wrappedValue }
let content: (Entity) -> Content
var body: some View {
ForEach(fetchRequest.wrappedValue, id: \.self) { result in
init(predicate: NSPredicate, sortDescriptors: [NSSortDescriptor], @ViewBuilder content: @escaping (Entity) -> Content) {
fetchRequest = FetchRequest<Entity>(entity: Entity.entity(), sortDescriptors: sortDescriptors, predicate: predicate)
self.content = content
Copy link

daniloc commented Aug 28, 2020

Example usage:

struct AView: View {
    @State var predicate = 
    @State var sortDescriptors = []

    var body: some View {

        List {
            EntityIterator(predicate: predicate, sortDescriptors: sortDescriptors) { (entity: EntityType) in


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment