For loop

I'm a new developer and try to code something.

I have a question about my for loop. My for loop is like:

**let** getraenke = ["Wasser" : 6, "Cola" : 1, "Orangensaft" : 3]

**for** (getraenke, bewertung) **in** getraenke {

print("\(getraenke) hat die Bewertung \(bewertung)")

}

and the result is like:

**Cola hat die Bewertung 1**

**Wasser hat die Bewertung 6**

**Orangensaft hat die Bewertung 3**

My question is, why ist "Cola" in the results at first place? Thank you for your answer and support.

You created a Dictionary named getraenke. Dictionaries don't keep their elements in any specific order.

You can find more about Collections here:
The Swift Programming Language: Redirect

2 Likes

That is just coincidence ("purer Zufall"):
You are using a Dictionary, and that manages the order of its elements on its own.
If you want to specify order, you need something like Array (or a datatype that is not available in the stdlib, like a sorted set).

2 Likes

There's also KeyValuePairs which can be made out of a dictionary literal

let getraenke: KeyValuePairs = ["Wasser" : 6, "Cola" : 1, "Orangensaft" : 3]

for (getraenke, bewertung) in getraenke {
    print("\(getraenke) hat die Bewertung \(bewertung)")
}
2 Likes

Thank you @Diggory!

Thank you to all for your answers and support! Thats great!

I'd suggest that you ask questions over #swift-users category. This category is about tinkering with the compiler (implementing new feature, fixing compiler bug, etc).