I'm a beginner for coding with swift. My first loop ist like:
let getraenke = ["Wasser" : 6, "Cola" : 1, "Orangensaft" : 3]
**for** (getraenke, bewertung) **in** getraenke {
print("\(getraenke) hat die Bewertung \(bewertung)")
}
The result ist **Cola hat die Bewertung 1**
**Wasser hat die Bewertung 6**
**Orangensaft hat die Bewertung 3**
Can you tell me why "Wasser" is not on the first line in results? Thank you for your answer
svanimpe
(Steven Van Impe)
2
Hi @crea1453,
A dictionary does not store its elements in a fixed order. Therefore, you cannot rely on the order of the elements being the same as in your declaration.
If you want to print a dictionary in a fixed order, you can for example, sort the keys alphabetically:
for key in getraenke.keys.sorted() {
print("\(key) hat die Bewertung \(getraenke[key]!)")
}
But if ordering is really important to you, you should prefer an array over a dictionary, as an array does store its elements in a fixed order.
Both types of collections just make different trade-offs of features vs performance of certain operations.
PS: To paste code on these forums, wrap it in triple backticks, like so:
```swift
your code here
```
4 Likes