Reputation: 85
I use this code :
AppDelegate.monthList = [Int: String]()
for index in stride(from: 1, to: 12, by: 1) {
AppDelegate.monthList[index] = "\(index)"
}
print("iosLog MONTH: \(AppDelegate.monthList)")
And result is :
iosLog MONTH: [11: "11", 10: "10", 2: "2", 4: "4", 9: "9", 5: "5", 6: "6", 7: "7", 3: "3", 1: "1", 8: "8"]
Whay ?!
I want add respectively the keys ( like PHP
or Java
)
Upvotes: 0
Views: 93
Reputation: 31645
Because Dictionary is unordered collection:
Every dictionary is an unordered collection of key-value pairs.
So, if you are aiming to get a sorted version of it, you should -logically- transform it into ordered collection, which is array. You could get:
Sorted array of AppDelegate.monthList
keys:
let sortedkeys = AppDelegate.monthList.keys.sorted()
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Sorted array of AppDelegate.monthList
values:
let sortedValues = AppDelegate.monthList.values.sorted()
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Or sorted array of tuples, as [(key, value)]
:
let sortedTuples = AppDelegate.monthList.sorted(by: <)
for tuple in sortedTuples {
print("\(tuple.key): \(tuple.value)")
}
Upvotes: 1