Will Mays Will Mays - 3 years ago 144
Swift Question

How to Sort Dictionary by Key of Strings?

I am using this code to sort a dictionary:

var sortedArray = dict.sorted(by: {$0.0 < $1.0})


and it is sorting but not the way I would like it to see below:

["1", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "2", "20", "21", "22", "23", "24", "3", "4", "5", "6", "7", "8", "9"]


insead of

["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"]


full dict:

["17": 00:00:89, "12": 00:00:89, "20": 00:00:89, "23": 00:00:89, "19": 00:00:89, "22": 00:00:89, "13": 00:00:89, "9": 00:00:00, "8": 00:00:00, "6": 00:00:89, "7": 00:17:13, "name": G. Snyder, "24": 00:00:89, "14": 00:00:89, "16": 00:00:89, "18": 00:00:89, "15": 00:00:89, "2": 00:02:02, "11": 00:00:89, "1": 00:01:01, "3": 00:01:59, "4": 00:03:12, "21": 00:00:89, "10": 00:00:33, "5": 00:06:15]


EDIT: (still not working)

var sortedArray = dict.sorted(by: {$0.0 < $1.0})
sortedArray.removeLast()
sortedArray = dict.sorted(by: {Int($0.0)! < Int($1.0)!})

Answer Source

Because the logic of how sorted(by:) is doing the comparison is related to the logic of the equality of the given elements, (you cannot sort an array of non-comparable elements), the output would be based on how strings comparing should be -since the given dict keys are strings- ("1" character is less than "2").

However, you might need to cast the key values to Ints and then sort:

let sorted = dict.sorted {
    if let key1Int = Int($0.key), let key2Int = Int($1.key) {
        return key1Int < key2Int
    }

    return true
}

At this point the sort should be valid even if the key value is uncastable to Int.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download