1

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!

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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))
}

1 Comment

for key in menu.keys.sort() iterate through the keys sorted alphabetically. It works as expected on my Mac.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.