更改 [Dictionary<String, String>] 数组中的键名

Changing the Key Names in a [Dictionary<String, String>] Array

我有一个字典数组 ([Dictionary<String, String>]),比方说,

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]
]

谢谢。

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

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([=10=]), ) })

let mappedArray = array.map { dic -> [String : Int] in
    // I wish this can be shortened using $ notation
    let mappedTuples = dic.flatMap { [(keysIndexedDictionary[[=10=]] ?? [=10=]) : ] }
    return Dictionary(uniqueKeysWithValues: mappedTuples)
}