Search code examples
iosarraysswiftkeyvaluepair

Creating an array of keys from a key value pair array


Originally I sorted a Dictionary which returned a key-value pair array and was trying to turn this into a Dictionary, when I was notified that a dictionary's order is random so therefore what I was doing is useless. I am trying to turn this key-value pair array into an array of just the keys and was wondering how to do it. Here is my code:

    let posts = ["post1" : 3, "post2" : 41, "post3" : 27]

    let sortedPS = posts.sorted { $1.1 < $0.1 }

posts is a Dictionary and sortedPS is of type Array<(key: String, value: Int)> and is a Key-Value Pair Array/Array of Tuples from what I can tell. sortedPS should be an array of tuples which looks like this:

    ["post2" : 41, "post3" : 27, "post1" : 3]

I want an array out of this which should look like this:

    ["post2", "post3", "post1"]

Please let me know how I can take the keys from sortedPS and produce an array.


Solution

  • You can use below short code to get all the keys from dictionary.

    let posts = ["post1" : 3, "post2" : 41, "post3" : 27]
    
    let sortedPS = posts.sorted { $1.1 < $0.1 }
    
    let keys = sortedPS.map { $0.key } // ["post2", "post3", "post1"]