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
-
1You don't have an array of integers. You have an array of strings.rmaddy– rmaddy07/11/2018 02:39:19Commented Jul 11, 2018 at 2:39
2 Answers 2
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
-
How does this compare (performance-wise) to mapping to int first, then sorting? (Assuming an
[Int]
is acceptable final result type)Alexander– Alexander07/11/2018 04:46:12Commented Jul 11, 2018 at 4:46 -
Gosh I feel dumb, sorry for wasting your time hahaTheLukeGuy– TheLukeGuy07/11/2018 12:43:31Commented Jul 11, 2018 at 12:43
The sort is calculating based on ASCII String Values,
Type Coersion to Int....
answered Jul 11, 2018 at 2:32
-
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.Alexander– Alexander07/11/2018 04:45:25Commented 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....Mark– Mark07/13/2018 06:04:44Commented Jul 13, 2018 at 6:04
lang-swift