Better Swift array sorting method?

I'm trying to sort an int array inside of Swift from greatest to least. The code I used is:

Array(data.keys).sorted(by: { $0 > $1 })

The array given is an array with integers 1 through 1,000. The results are:

999, 998, 997 ... 991, 990, 99, 989 ... 802, 801, 800, 80, 8, 799, 798 ...

The results I want are:

999, 998, 997 ... 991, 990, 989 ... 802, 801, 800, 799, 798 ...

2 answers

  • answered 2018-07-11 02:32 Mark

    The sort is calculating based on ASCII String Values,

    Type Coersion to Int....

  • answered 2018-07-11 02:42 Leo Dabus

    Your dictionary keys are strings not integers. You can sort them comparing those keys using numeric options as follow:

    let sorted = data.keys.sorted { 
        $0.compare($1, options: .numeric) == .orderedDescending 
    }