UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 85: HotProspects Challenges - Comparable, and a filtering question

Forums > 100 Days of SwiftUI

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 < ?

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.