Tamarisk Tamarisk - 3 months ago 20
Swift Question

Get keys of Dictionary in array in original order

Let's say I have a dictionary

let dict = [
"Joe":"D.",
"Ben":"K.",
"Kyle":"R.",
"Matt":"L."
]


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?

i.e.

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

Answer

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.")]
        print(array)
//        [("Joe", "D."), ("Ben", "K."), ("Kyle", "R.")]
        let keys = array.map { $0.0 }
        print(keys)
//        ["Joe", "Ben", "Kyle"]