Reputation: 1516
In order to create table view programmatically i have a menu setup like below, it contains sections as well as cells.
var menu = [
"section 1": [
"point a",
"point b",
"point c"
],
"section 2": [
"point a",
"point b",
"point c",
"point d",
"point e"
],
"section 3": [
"point a"
]
]
struct Sections {
var sectionName : String!
var sectionObjects : [String]!
}
var sections = [Sections]()
for (key, value) in menu {
print("\(key) -> \(value)")
sections.append(Sections(sectionName: key, sectionObjects: value))
}
So i want it exactly inserted in this order (section 1 -> section 2 -> section 3).
But it is actually inserted in an other order(from print):
section 2 -> ["point a", "point b", "point c", "point d", "point e"]
section 1 -> ["point a", "point b", "point c"]
section 3 -> ["point a"]
I absolutely dont know why the order is changed in the menu array. Anybody can imagine why or have some suggestions?
Thanks and Greetings!
Upvotes: 1
Views: 577
Reputation: 93191
That's because Dictionary
has no order. You must sort the keys yourself before iterating over them:
for key in menu.keys.sort() {
let value = menu[key]!
sections.append(Sections(sectionName: key, sectionObjects: value))
}
Upvotes: 1
Reputation: 2035
Dictionaries in Swift don't have an order to them. So when you iterate through one, you won't necessarily encounter them in the same order that they were added.
Check out this answer for more detail: https://stackoverflow.com/a/24111700/3517395
Upvotes: 2