TheLukeGuy
TheLukeGuy

Reputation: 180

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 ...

Upvotes: 1

Views: 91

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236260

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 
}

Upvotes: 3

Mark
Mark

Reputation: 515

The sort is calculating based on ASCII String Values,

Type Coersion to Int....

Upvotes: -2

Related Questions