How can I merge two arrays into a dictionary? (6个答案)
2年前关闭。
我有两个字符串数组,下面是定义,因此如何从一系列键值对创建字典。
let cityNames = ["Riyadh", "Mecca", "Sultanah", "Buraydah", "Al Qarah"]
let nearestDistances = [84.24, 41.37, 45.37, 57.96, 78.78]
任何帮助将不胜感激。
如前所述,自Xcode 9起,Swift标准库为此类情况提供了方便的 Dictionary
initializer:
init<S>(uniqueKeysWithValues keysAndValues: S)
where S: Sequence, S.Element == (Key, Value)
从给定序列的键值对创建一个新字典。
如果不太熟悉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>