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 ...
rmaddy
319k44 gold badges548 silver badges590 bronze badges
asked Jul 11, 2018 at 2:19
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 
}
answered Jul 11, 2018 at 2:42
2
  • How does this compare (performance-wise) to mapping to int first, then sorting? (Assuming an [Int] is acceptable final result type) Commented Jul 11, 2018 at 4:46
  • Gosh I feel dumb, sorry for wasting your time haha Commented Jul 11, 2018 at 12:43
-2

The sort is calculating based on ASCII String Values,

Type Coersion to Int....

answered Jul 11, 2018 at 2:32
2
  • 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. Commented Jul 11, 2018 at 4:45
  • 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.... Commented Jul 13, 2018 at 6:04

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.