Tamarisk Tamarisk - 5 months ago 28
Swift Question

Get keys of Dictionary in array in original order

Let's say I have a dictionary

let dict = [

If I wanted an array of the keys of this dictionary I do:

let keys = Array(dict.keys)

But this prints in a seemingly random order:

["Ben", "Joe", "Matt", "Kyle"]

Is there a way to get an array of keys that with the same order as the origin dictionary?


["Joe", "Ben", "Kyle", "Matt"]


Dictionaries don't have order. When we add new element to dictionary we don't now the order. You can use Array of Tuple

        let array = [("Joe", "D."), ("Ben", "K."), ("Kyle", "R.")]
//        [("Joe", "D."), ("Ben", "K."), ("Kyle", "R.")]
        let keys = array.map { $0.0 }
//        ["Joe", "Ben", "Kyle"]