Last active
May 7, 2021 20:54
-
-
Save daniloc/65f79c3fe1d77c3e82d29b0d15af59a9 to your computer and use it in GitHub Desktop.
EntityIterator: Wrapper around SwiftUI's ForEach to iterate through Core Data entities according to a predicate and sort descriptors you can change at runtime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//adapted via: https://www.hackingwithswift.com/books/ios-swiftui/dynamically-filtering-fetchrequest-with-swiftui | |
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 | |
self.content(result) | |
} | |
} | |
init(predicate: NSPredicate, sortDescriptors: [NSSortDescriptor], @ViewBuilder content: @escaping (Entity) -> Content) { | |
fetchRequest = FetchRequest<Entity>(entity: Entity.entity(), sortDescriptors: sortDescriptors, predicate: predicate) | |
self.content = content | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: