如何从 swift 中的键值对(元组)序列创建一个双字符串数组
How to create a two string array from a sequence of key-value pairs (tuple) in swift
我有两个字符串数组,它定义如下如何从一系列键值对创建字典。
let cityNames = ["Riyadh", "Mecca", "Sultanah", "Buraydah", "Al Qarah"]
let nearestDistances = [84.24, 41.37, 45.37, 57.96, 78.78]
如有任何帮助,我们将不胜感激。
只需zip
将它们组合成一个循环
var dictionary = [String: Double]()
for (city, distance) in zip(cityNames, nearestDistances){
dictionary[city] = distance
}
更好的是,你可以为它做一个很好的扩展:
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)
如前所述,自 Xcode 9 起,Swift 标准库 为此类情况提供了方便的 Dictionary
initializer:
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.
如果不太熟悉 Swift 泛型,这可能难以阅读;)不过,用法非常简单:
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)
打印:
[
"Buraydah": 57.96,
"Al Qarah": 78.78,
"Mecca": 41.37,
"Riyadh": 84.24,
"Sultanah": 45.37
]
最后,生成的字典类型就是您所期望的:
print(type(of: dict)) // Dictionary<String, Double>
我有两个字符串数组,它定义如下如何从一系列键值对创建字典。
let cityNames = ["Riyadh", "Mecca", "Sultanah", "Buraydah", "Al Qarah"]
let nearestDistances = [84.24, 41.37, 45.37, 57.96, 78.78]
如有任何帮助,我们将不胜感激。
只需zip
将它们组合成一个循环
var dictionary = [String: Double]()
for (city, distance) in zip(cityNames, nearestDistances){
dictionary[city] = distance
}
更好的是,你可以为它做一个很好的扩展:
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)
如前所述,自 Xcode 9 起,Swift 标准库 为此类情况提供了方便的 Dictionary
initializer:
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.
如果不太熟悉 Swift 泛型,这可能难以阅读;)不过,用法非常简单:
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)
打印:
[
"Buraydah": 57.96,
"Al Qarah": 78.78,
"Mecca": 41.37,
"Riyadh": 84.24,
"Sultanah": 45.37
]
最后,生成的字典类型就是您所期望的:
print(type(of: dict)) // Dictionary<String, Double>