2
var letters = ["a": "Alpha", "b": "Bravo", "c": "Charlie", "d": "Delta"]

for (letter, pilotAlphabet) in letters {
    print("\(letter) stands for \(pilotAlphabet)")
}

This is my code on the Playgrounds. The console gives this:

b stands for Bravo
a stands for Alpha
d stands for Delta
c stands for Charlie

I wonder why this outcome is not in the order I given.

2 Answers2

3

letters is a Dictionary, whose keys and values are both Strings. A Dictionary is an unordered collection by definition, so when iterating through the key-value pairs of the dictionary, the ordering won't be the same as the order in which you added the values to the dictionary, nor will it be alphabetical.

If you need to display the key-value pairs in alphabetical order, you can do so by calling sorted on the Dictionary and iterating through the resulting Array of tuples.

var letters = ["a": "Alpha", "b": "Bravo", "c": "Charlie", "d": "Delta"]

for (letter, pilotAlphabet) in letters.sorted(by: {$0.key<$1.key}) {
    print("\(letter) stands for \(pilotAlphabet)")
}

Output:

a stands for Alpha
b stands for Bravo
c stands for Charlie
d stands for Delta
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • I did not know ".sorted" and thanks to you I have learnt something new! And I get the same output as the one you share. – Cihan Necmi Gunal Aug 27 '18 at 13:34
  • Note that `Dictionary.sorted()` maps the dictionary to an array of tuples (in your case `(key:String, value: String)`.) – Duncan C Aug 27 '18 at 13:59
0

When you iterate over the contents of a Dictionary you do so as an unordered collection of key-value pairs. The order is documented to be stable between mutations but otherwise unpredictable.

David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205