假设我有这样的数组:
var array = ["zero","one","two", "three"]
我想将它转换为Dictionary
,但键作为数组元素的索引,值是自己的元素:
var dic = [0:"zero", 1:"one", 2:"two", 3:"three"]
答案 0 :(得分:2)
您可以使用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"]