【发布时间】:2018-07-12 14:20:06
【问题描述】:
假设,我有这样的数组:
var array = ["zero","one","two", "three"]
我想将其转换为Dictionary,但键作为数组元素的索引,值是它自己喜欢的元素:
var dic = [0:"zero", 1:"one", 2:"two", 3:"three"]
【问题讨论】:
标签: arrays swift dictionary type-conversion
假设,我有这样的数组:
var array = ["zero","one","two", "three"]
我想将其转换为Dictionary,但键作为数组元素的索引,值是它自己喜欢的元素:
var dic = [0:"zero", 1:"one", 2:"two", 3:"three"]
【问题讨论】:
标签: arrays swift dictionary type-conversion
您可以使用Dictionary.uniqueKeysWithValues 和zip 的组合:
var array = ["zero","one","two", "three"]
var dict = Dictionary(uniqueKeysWithValues: zip(array.indices, array))
print(dict) // [0:"zero", 1:"one", 2:"two", 3:"three"]
【讨论】:
0..<array.count。
zip(array.indices, array)