0

I have an array that has integers as keys, and strings for values

var dictionary = [Int: String]()

All of these try's either end in compile error for Swift 5:

dictionary = dictionary.keys.sorted()

dictionary = (dictionary.sorted{ $0.key < $1.key })

dictionary = dictionary.sorted { $0.0 < $1.0 } .map { $0.1 }

reverseSortedValues = dictionary.sorted { $0.0 > $1.0 } .map { $0.1 }

dictionary = profileImagesDictionary.sorted(by: { $0.0.compare($1.0) == .OrderedAscending })

dictionary = profileImagesDictionary.sorted { $0.key

Code:

profileImagesDictionary = [Int : String](uniqueKeysWithValues: profileImagesDictionary.sorted{ $0.key > $1.key})

Console Output printed keys

before: dictionary = [3, 1, 2, 4, 0]

after: dictionary = [3, 0, 2, 1, 4]

I need it to rearrange the dictionary / actually sort it by keys.

So like instead of:

dictionary = [1: "a", 3: "c", 2: "b"]

It after being sorted would be:

dictionary = [1: "a", 2: "b", 3: "c"]
Hunter
  • 1,321
  • 4
  • 18
  • 34
  • 3
    Dictionaries are unordered. They can't be sorted. You can sort the keys as shown in the answers and the duplicates and then iterate over the resulting array to subscript the dictionary – Paulw11 Feb 15 '20 at 05:24
  • 1
    Dictionaries are by nature unsortable. This is a critical concept--you cannot sort a dictionary as-is. Dictionaries use a hash algorithm to map keys to value locations. If you want a "sorted dictionary" (in quotes because, again, there's no such thing) you have to get the dictionary keys into an array, then sort that array, then iterate through the sorted keys pulling values from the dictionary into another array of values that are sorted by key. – par Feb 15 '20 at 05:27

2 Answers2

0

Simply give the following code to print sorted keys.

print(dictionary.keys.sorted)
Frankenstein
  • 15,732
  • 4
  • 22
  • 47
0

Here you have a Dictionary not an Array, to sort your dictionary based on your keys you could use let sortedKeys = Array(dictionary.keys).sort(<) , but it only contains keys in array

Mac3n
  • 4,189
  • 3
  • 16
  • 29
  • Unfortunately I need to actually sort the existing dictionary in this question. – Hunter Feb 15 '20 at 05:22
  • 1
    sort wouldn't make sense to `Dictionary`. With `Dictionary`, you check if you have a value associated with a given key, not where the value is–it has no sense of order – Mac3n Feb 15 '20 at 05:29