Ali_C
Ali_C

Reputation: 225

accessing keys from a returned sorted array of dictionaries in Swift 4

I have an array of dictionaries called groupedDictionary defined below:

// The type is [String : [SingleRepository]]
let groupedDictionary = Dictionary(grouping: finalArrayUnwrapped) { (object) -> String in
        var language = "Not Known to GitHub"
        if let languageUnwrapped = object.language {
            language = languageUnwrapped
        }

        return language
    }

I can easily get all the keys as follows:

let keys = groupedDictionary.keys

However, when I try to sort this array using sorted(by:) in Swift 4, I successfully get the sorted array back with the type [(key: String, value: [SingleRepository])].

// the type is [(key: String, value: [SingleRepository])]
    let sortedGroupedDictionary =  groupedDictionary.sorted(by: { ($0.value.count) > ($1.value.count) })

How can I get all of the keys from sortedGroupedDictionary?

It is not possible to call ".keys" on sortedGroupedDictionary, since it has a different type.

Please note: I'm not trying to sort the array based on the keys. I did sort the array that consists of dictionaries, based on a predicate which is size of the array containing each value, now I just want to extract the keys.

Upvotes: 0

Views: 115

Answers (1)

waldrumpus
waldrumpus

Reputation: 2590

The method Dictionary.sorted(by:) returns the keys and values of your original dictionary as an array of key-value pairs, sorted by the predicate you pass as an argument. That means that the first element of each tuple is the key you're looking for.

You can go through the result like this:

for (key, value) in sortedGroupedDictionary {
    // handle this key-value-pair
}

If all you need is an array of the sorted keys, you can get that using

sortedGroupedDictionary.map { $0.key }

Upvotes: 1

Related Questions