【问题标题】:Turning an indexed array into a dictionary in Swift在 Swift 中将索引数组转换为字典
【发布时间】:2018-06-06 01:28:29
【问题描述】:

所以我在这里找到了这种方法,但我不明白如何实现它。

extension Collection  {
    var indexedDictionary: [Int: Element] {
        return enumerated().reduce(into: [:]) { $0[$1.offset] = $1.element }
    }
}

所以假设我有一个字符串数组,比如

var someArray: [String] = ["String", "String", "String"...etc]

我想被索引,使最终结果成为像

这样的字典

[1: "string", 2: "string":..etc]

使用这种方法,我该如何实现呢?就像我在哪里将 someArray 放入该代码中?

【问题讨论】:

  • let indexedDict = someArray.indexedDictionary
  • indexedDictionary 是一个与count 没有太大区别的属性(以它的调用方式,而不是它的含义)。如果您现在如何访问数组的count,那么您知道如何访问数组的indexedDictionary
  • 我或那个 vacawama 在哪里?
  • Rmaddy 你在说什么?我在 someArray.count 中使用 count
  • 当心,Maddy,我想,在否决投票按钮上非常快。从问题标题和给出的示例中并不清楚这与indexedDictionary 有关。如果我的回答几乎立即被否决,现在已删除

标签: arrays swift dictionary indexed


【解决方案1】:

这个扩展:

extension Collection  {
    var indexedDictionary: [Int: Element] {
        return enumerated().reduce(into: [:]) { $0[$1.offset] = $1.element }
    }
}

indexedDictionary 属性添加到Swift 中的所有Collections。数组是 Collection,因此当您将此扩展名添加到顶层的 Swift 源文件时,数组会将此属性添加到其中(不要将其放在另一个 classstruct 或 @987654327 中@)。您只需将其添加到项目中的一个文件中,然后新属性将在每个文件中都可以访问。

然后,您只需在代码中的任何数组上调用indexedDictionary,它就会返回[Int : Element] 类型的Dictionary,其中Element 表示原始数组中的类型。因此,如果您的数组myArray 的类型为[String],那么myArray.indexedDictionary 将返回Dictionary 类型的[Int : String]


示例:

let arr1 = ["a", "b", "c"]
let dict1 = arr1.indexedDictionary
print(dict1)

输出:

[2: "c", 0: "a", 1: "b"]

// It works with dictionary literals
let dict2 = [5, 10, 15].indexedDictionary
print(dict2)

输出:

[2: 15, 0: 5, 1: 10]

  let arr3: [Any] = [true, 1.2, "hello", 7]
  print(arr3.indexedDictionary)

输出:

[2: "hello", 0: true, 1: 1.2, 3: 7]

注意:字典是无序的,因此即使顺序不可预测,键到值的映射也是您所期望的。

【讨论】:

  • 祝福你和你的心。
【解决方案2】:
let result = someArray.reduce([:]) { (dic, val) -> [Int:String] in
    let index = someArray.index(of: val)
    var mutableDic = dic
    mutableDic[index!] = val
    return mutableDic
}

【讨论】:

    猜你喜欢
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 2021-10-18
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多