codebot
codebot

Reputation: 2646

Sort dictionary by value in swift

I have a dictionary as [String: [String]]. Data looks like,

Province
  |- State 1
  |    |- A
  |    |- C
  |    |- E
  |- State 2
       |- B
       |- A
       |- D

I tried to sort this as,

let sortedResult = plistData.sorted{ $0.key < $1.key }.map { [$0.key: $0.value.sorted()] }

But this gives me an [[String : [String]]] type array. How may I fix this to get a [String : [String]].? Need to sort this by all values

Upvotes: 0

Views: 1416

Answers (2)

Frankenstein
Frankenstein

Reputation: 16341

Dictionaries can't be sorted, they don't maintain a position like array. You can sort the keys though, and from the sorted keys get the value from the dictionary:

let dictionary = [String: [String]]()
print(dictionary.keys.sorted())
for key in dictionary.keys.sorted() {
    print(dictionary[key]?.sorted())
}

Edit: I saw you mention in the comments about the requirement change. If you only want to sort the value here is how:

let dictionary = [String: [String]]()
let sortedDictionary = dictionary.mapValues { $0.sorted() }

Upvotes: 0

vacawama
vacawama

Reputation: 154583

In the comments, you specified that you want to sort the value arrays. You can accomplish this using mapValues and sorted like this:

let sortedResult = plistdata.mapValues { $0.sorted() }

Note: Dictionaries in Swift are unordered (have no specified order), so it isn't possible to put the keys into a specific order. If you'd like to display the keys in a specific sorted order, then sort them into a separate array using let sortedKeys = plistdata.keys.sorted().

Upvotes: 1

Related Questions