I managed to get the filters working OK by making my Prospect class conform to Comparable. I figured since name is not a guaranteed unique identifier in the context of this app, I added further logic to sort based on id.
class Prospect: Identifiable, Codable, Comparable {
static func < (lhs: Prospect, rhs: Prospect) -> Bool {
if lhs.name != rhs.name {
return lhs.name < rhs.name
} else {
return lhs.id < rhs.id
}
}
static func == (lhs: Prospect, rhs: Prospect) -> Bool {
lhs.id == rhs.id
}
With that in place, I updated the ProspectView to include a new computed property:
var filterProspects: [Prospect] {
switch filter {
case .none:
return prospects.people
case .contacted:
return prospects.people.filter() { $0.isContacted }
case .uncontacted:
return prospects.people.filter() { !$0.isContacted }
}
}
var sortedProspects: [Prospect] {
switch sort {
case .byName:
return filterProspects.sorted()
case .byDate:
return filterProspects.sorted { lhs, rhs in
if lhs.date != nil && rhs.date != nil && lhs.date != rhs.date {
return lhs.date! < rhs.date!
} else { return lhs.id < rhs.id }
}
}
}
It works, but I don't love it. My first inclination was to try to combine these two computed properties into one, possibly using dual switch statements, but I ran into a wall there.
Is there a way to accomplish what I'm going for?
Or... is there a way to add additional types of sorting within the Prospect class itself besides the required static func <
?