I am at day 85 of the HackingWithSwiftUI challenge and I just can't get the sorting of the Prospect objects to work. I even looked back to day 58 when Paul Hudson explained how to change the sorting parameters for the SwiftData query - but that didn't work.
Here's my Prospect object:
import Foundation
import SwiftData
@Model
class Prospect {
var name: String
var emailAddress: String
var isContacted: Bool
var dateAdded: Date = Date.now
init(name: String, emailAddress: String, isContacted: Bool) {
self.name = name
self.emailAddress = emailAddress
self.isContacted = isContacted
}
}
I just added dateAdded when creating a new prospect.
In ProspectsView, where the query is shown, thise are the related code snippets:
@Query var prospects: [Prospect]
@State private var sortOrder = [
SortDescriptor(\Prospect.dateAdded),
SortDescriptor(\Prospect.name)
]
init(filter: FilterType) {
self.filter = filter
if filter != .none {
let showContactedOnly = filter == .contacted
_prospects = Query(filter: #Predicate {
$0.isContacted == showContactedOnly
}, sort: sortOrder)
} else {
_prospects = Query(sort: sortOrder)
}
}
This one is for selecting the sort order - but that works just fine:
Menu("Sort", systemImage: "arrow.up.arrow.down") {
Picker("Sort", selection: $sortOrder) {
Text("Sort by Name")
.tag([
SortDescriptor(\Prospect.name),
SortDescriptor(\Prospect.dateAdded)
])
Text("Sort by Date added")
.tag([
SortDescriptor(\Prospect.dateAdded),
SortDescriptor(\Prospect.name)
])
}
}
The code compiles - it just doesn't do anything when changing the sort order.
Where is my error?