Search code examples
swiftsortingswift3swift-dictionary

Sort Dictionary by value with tie Element should not change their order


I have a Dictionary of type [String: Int] and its value is

let dic = [“a”:4, “b”:3, “c”:3]

I want to sort the dictionary by value and using method

dic  = dic.sorted(by: { $0.value < $1.value })

Result

dic = [“c”:3, “b”:3, “a”:4]

It is sorting the dictionary but i want the values which are same should not to be sort or change their order, for example, I want this result

dic = [“b”:3, “c”:3, “a”:4]

Solution

  • The main problem here is that dictionary is an unordered collection, so trying to sort it is not the best thing to do.

    If you want to store the score values for your game (for a leader-board i.e.) you can use tuples.

    typealias Score = (username: String, score: Int)
    

    Then use can create an array of that tuples and sort them any way you want.

    var scores = [Score]()
    
    // fill the scores
    scores.append(("a", 4))
    scores.append(("b", 3))
    scores.append(("c", 3))
    
    scores.sort {
        return $0.score < $1.score || ($0.score == $1.score && $0.username.localizedCaseInsensitiveCompare($1.username) == .orderedAscending)
    }