letters
is a Dictionary
, whose keys and values are both String
s. 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