I have almost completed the challenge on day 59, but I am trying to figure out part 3 of the challenge where we are supposed to allow our own view FilteredList
to accept an array of SortDescriptor
.
Apparently [SortDescriptor]
is not a valid type. Obviously I am not understanding something, but I can not figure out what I am missing. Can anybody give me a pointer on how to proceed?
FilteredList
import CoreData
import SwiftUI
struct FilteredList<T: NSManagedObject, Content: View>: View {
@FetchRequest var fetchRequest: FetchedResults<T>
let content: (T) -> Content
var body: some View {
List(fetchRequest, id: \.self) { item in
self.content(item)
}
}
init(filterKey: String, filterValue: String, predicate: MyPredicate, sortDescriptors: [SortDescriptor], @ViewBuilder content: @escaping (T) -> Content) {
var stringPredicate: String
switch predicate {
case .beginsWith:
stringPredicate = "BEGINSWITH"
case .contains:
stringPredicate = "CONTAINS"
case .predIN:
stringPredicate = "IN"
}
_fetchRequest = FetchRequest<T>(sortDescriptors: sortDescriptors, predicate: NSPredicate(format: "%K \(stringPredicate) %@", filterKey, filterValue))
self.content = content
}
}
enum MyPredicate {
case beginsWith, contains, predIN
}
ContentView
import CoreData
import SwiftUI
struct ContentView: View {
@Environment(\.managedObjectContext) var moc
@State private var lastNameFilter = "A"
var body: some View {
VStack {
// list of matching singers
FilteredList(filterKey: "lastName",
filterValue: lastNameFilter,
predicate: .beginsWith,
sortDescriptors: [
SortDescriptor(\.wrappedLastName),
SortDescriptor(\.wrappedFirstName, order: .reverse)
]) { (singer: Singer) in
Text("\(singer.wrappedFirstName) \(singer.wrappedLastName)")
}
}
}
}