lws803
lws803

Reputation: 947

Swift how to sort array dictionary by key values

I have a list of URL and its respective favourite counts obtained from firebase database appended into an array of dictionaries as such:

dictionaryArray = [[1: URL1], [2: URL2], [1: URL3]]

I understand that we can sort the array of dictionaries by using .sort but that removes dictionaries with similar keys like in this case.

how do I sort it such that I get an array of the url ordered by their keys to this:

urlArray = [URL2, URL1, URL3] 

since URL2 has the higher key whereas URL1 and URL3 have similar keys

Upvotes: 0

Views: 1758

Answers (2)

Parth Adroja
Parth Adroja

Reputation: 13514

You can sort by using sort descriptors available like below.

var descriptor: NSSortDescriptor = NSSortDescriptor(key: "name", ascending: true)
var sortedResults: NSArray = results.sortedArrayUsingDescriptors([descriptor])

Upvotes: -1

Thomas G.
Thomas G.

Reputation: 1003

You could use higher-order functions sorted and flatMap nested together like so:

let sortedURLs = dictionaryArray
                    .sorted(by: { $0.keys.first! > $1.keys.first! })
                    .flatMap({ $0.values.first! })

Note: watch out of forced unwrapped optionals it is working here but could lead to an exception

Upvotes: 2

Related Questions