1

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 ...
1
  • 1
    You don't have an array of integers. You have an array of strings. Commented Jul 11, 2018 at 2:39

2 Answers 2

3

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 
}
Sign up to request clarification or add additional context in comments.

2 Comments

How does this compare (performance-wise) to mapping to int first, then sorting? (Assuming an [Int] is acceptable final result type)
Gosh I feel dumb, sorry for wasting your time haha
-2

The sort is calculating based on ASCII String Values,

Type Coersion to Int....

2 Comments

Swift doesn't coerce Strings/Characters to ASCII (for one, because they're utf encoded (8/16/32, I don't remember), and it doesn't do almost any coercions implicitly, in general.
Poor use of language by me... I was just pointing out that the sort was occurring based on String/character rather than Int sort which is what the correct solution does....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.