Handling Ties in a Custom Ranking Algorithm with Swift
I'm relatively new to this, so bear with me... I'm implementing a custom ranking algorithm in Swift that needs to handle ties in scores. The goal is to sort a list of candidates based on their scores and then by their names alphabetically in case of ties. However, I'm running into an scenario where the sorting doesn't seem to prioritize alphabetical order after scoring, causing unexpected behavior. Here's a simplified version of what I have: ```swift struct Candidate { let name: String let score: Int } let candidates = [ Candidate(name: "Alice", score: 95), Candidate(name: "Bob", score: 95), Candidate(name: "Charlie", score: 90) ] let sortedCandidates = candidates.sorted { (a, b) in if a.score == b.score { return a.name < b.name } return a.score > b.score } ``` Running this code gives me the following output: ``` [Alice, Bob, Charlie] ``` Which is correct, but when I have a list like this: ```swift let candidates = [ Candidate(name: "Eve", score: 85), Candidate(name: "David", score: 90), Candidate(name: "Bob", score: 90), Candidate(name: "Charlie", score: 85) ] ``` The sorted output is: ``` [David, Bob, Charlie, Eve] ``` But I expected it to give me [Bob, David, Charlie, Eve]. I suspect the scenario is with how I'm handling the tie-breaking. I also tried using the `compare` method with strings but that didn't resolve the scenario. Any insights on how I can correctly implement this with proper tie-breaking for names in Swift? Thanks! What's the best practice here? Thanks for your help in advance! I'm working on a REST API that needs to handle this.