Reputation: 939
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"]
Upvotes: 0
Views: 129
Reputation: 5130
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"]
Upvotes: 2