【问题标题】:Array to Dictionary (without Loop)数组到字典(无循环)
【发布时间】: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


【解决方案1】:

您可以使用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"]

【讨论】:

  • 0..<array.count
  • zip(array.indices, array)
猜你喜欢
  • 2016-01-05
  • 2015-05-19
  • 2015-01-04
  • 2016-05-20
  • 1970-01-01
  • 1970-01-01
  • 2020-02-10
  • 1970-01-01
  • 2018-12-01
相关资源
最近更新 更多