数组到字典(没有循环)

时间:2018-02-02 06:06:45

标签: arrays swift dictionary type-conversion

假设我有这样的数组:

var array = ["zero","one","two", "three"]

我想将它转换为Dictionary,但键作为数组元素的索引,值是自己的元素:

var dic = [0:"zero", 1:"one", 2:"two", 3:"three"]

1 个答案:

答案 0 :(得分:2)

您可以使用Dictionary.uniqueKeysWithValueszip的组合:

var array = ["zero","one","two", "three"]
var dict = Dictionary(uniqueKeysWithValues: zip(array.indices, array))
print(dict) // [0:"zero", 1:"one", 2:"two", 3:"three"]