1

I have two string array and it's define following so how to create a dictionary from a sequence of key-value pairs.

let cityNames = ["Riyadh", "Mecca", "Sultanah", "Buraydah", "Al Qarah"]
let nearestDistances = [84.24, 41.37, 45.37, 57.96, 78.78]

Any help would be greatly appreciated.

BuLB JoBs
  • 841
  • 4
  • 20

2 Answers2

3

Just zip them up and combine them in a loop

var dictionary = [String: Double]()

for (city, distance) in zip(cityNames, nearestDistances){
    dictionary[city] = distance
}

Better yet, you can make a nice extension for it:

extension Dictionary{
    init(keys: [Key], values: [Value]){
        self.init()
        for (key, value) in zip(keys, values){
            self[key] = value
        }
    }
}

let dictionary = Dictionary<String, Double>(keys: cityNames, values: nearestDistances)
Michael Hulet
  • 3,253
  • 1
  • 16
  • 33
  • 3
    You could also use the new initializers: https://developer.apple.com/documentation/swift/dictionary/2894798-init / https://developer.apple.com/documentation/swift/dictionary/2892961-init (depending if the keys are unique or not) – nathan Oct 31 '17 at 14:06
1

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>
Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85