As already mentioned, since Xcode 9, the Swift Standard Library provides a handy Dictionary
initializer for such cases:
init<S>(uniqueKeysWithValues keysAndValues: S)
where S: Sequence, S.Element == (Key, Value)
Creates a new dictionary from the key-value pairs in the given sequence.
This might be difficult to read if aren't too familiar with Swift generics ;) Nevertheless, the usage is pretty straightforward:
let cityNames = ["Riyadh", "Mecca", "Sultanah", "Buraydah", "Al Qarah"]
let nearestDistances = [84.24, 41.37, 45.37, 57.96, 78.78]
let dict = Dictionary(uniqueKeysWithValues: zip(cityNames, nearestDistances))
print(dict)
prints:
[
"Buraydah": 57.96,
"Al Qarah": 78.78,
"Mecca": 41.37,
"Riyadh": 84.24,
"Sultanah": 45.37
]
Finally, the resulting dictionary type is what you would expect:
print(type(of: dict)) // Dictionary<String, Double>