【问题标题】:Changing the Key Names in a [Dictionary<String, String>] Array更改 [Dictionary<String, String>] 数组中的键名
【发布时间】:2020-03-23 16:42:26
【问题描述】:

我有一个字典数组 ([Dictionary&lt;String, String&gt;]),比如说,

let dict0 = ["0": 1, "1": 2, "2": 4]
let dict1 = ["0": 5, "1": 4, "2": 8]
let dict2 = ["0": 3, "1": 9, "2": 7]
let array = [dict0, dict1, dict2]

所以它看起来像下面这样。

[
  ["0": 1, "1": 2, "2": 4], 
  ["2": 8, "0": 5, "1": 4], 
  ["2": 7, "1": 9, "0": 3]
]

假设我有一个键数组 ([String]),例如

let keys = ["ant", "bee", "spider"]

是否有一种简单的方法可以更改我的数组的键,使其如下所示?

[
  ["ant": 1, "bee": 2, "spider": 4], 
  ["spider": 8, "ant": 5, "bee": 4], 
  ["spider": 7, "bee": 9, "ant": 3]
]

谢谢。

【问题讨论】:

    标签: arrays swift dictionary swift5


    【解决方案1】:

    实际上并不知道您所说的简单方法是什么意思,但以下内容将完成工作。

    let dict0 = ["0": 1, "1": 2, "2": 4]
    let dict1 = ["0": 5, "1": 4, "2": 8]
    let dict2 = ["0": 3, "1": 9, "2": 7]
    let array = [dict0, dict1, dict2]
    
    let keys = ["ant", "bee", "spider"]
    let keysIndexedDictionary = Dictionary(uniqueKeysWithValues: keys.enumerated().map { (String($0), $1) })
    
    let mappedArray = array.map { dic -> [String : Int] in
        // I wish this can be shortened using $ notation
        let mappedTuples = dic.flatMap { [(keysIndexedDictionary[$0] ?? $0) : $1] }
        return Dictionary(uniqueKeysWithValues: mappedTuples)
    }
    

    【讨论】:

    • 如果您在键数组中有 duplicate 个条目,则必须考虑 this。或者,也许您可​​以通过将键集合设置为 Set 而不是 Array 来消除这种可能性,但是您将丢失集合中元素的顺序,因为 Set 处于无序状态。
    猜你喜欢
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    相关资源
    最近更新 更多