Dictionary is unordered. This means that whatever order you see the KVPs in code is not guaranteed to be maintained. The sort
call only says to sort by values, so the keys can be in whatever order they want.
Also note that Swift's sorted(by:)
is not stable. This means things that are considered equal are not guaranteed to maintain their order.
Therefore, you can't really do anything about it if you insist on using Swift's built in algorithms. You could write an insertion sort (a stable sorting algorithm) yourself and use it though.
Another solution is to order the KVPs by values, then by keys:
let newDict = dict.sorted(by: { $0.value == $1.value ? $0.key < $1.key : $0.value < $1.value })
Obviously this will only work if your player names are ordered lexicographically originally.
Alternatively, create a Player
struct and use an array of Player
s:
struct Player {
let name: String
var score: Int
}