使用数组方法映射来聚合具有数组的字典数组

时间:2015-10-07 06:17:08

标签: ios swift

我有array代表(例如)一周中的几天:

["Monday", "Tuesday", "Wed", "Thursday", "Friday", "Sat", "Sunday"]

我的第一个数组的SAME大小为array of dictionaries,每个Dictionary只包含一个key/value

[["temp": 11], ["temp": 12], ["temp": 13], ["temp": 14], ["temp": 15], ["temp": 16], ["temp": 17]]

每个温度对应于第一个数组中相同索引的日期。

是否有办法使用数组方法map(transform: (Self.Generator.Element) throws -> T)将我的字典数组转换为以下字典:

 ["Monday": 11, "Tuesday": 12, "Wed": 13, "Thursday": 14, "Friday": 15, "Sat": 16, "Sunday": 17]

2 个答案:

答案 0 :(得分:1)

嗯,您只能从Array而不是map返回Dictionary。以下是另一种方法:

var test1 = [["temp": 11], ["temp": 12], ["temp": 13], ["temp": 14], ["temp": 15], ["temp": 16], ["temp": 17]]
var myArray = ["Monday", "Tuesday", "Wed", "Thursday", "Friday", "Sat", "Sunday"]
var finalArray = [Dictionary<String,Int?>]()

for day in myArray {
    let itemIndex = myArray.indexOf(day)
    let itemDict = test1[itemIndex!]
    let value = itemDict["temp"] as Int?
    let changedDict = [day : value]
    finalArray.append(changedDict)
}

答案 1 :(得分:1)

这显然适用于zip

var test1: [[String: Any]] = [["temp": 11], ["temp": 12], ["temp": 13], ["temp": 14], ["temp": 15], ["temp": 16], ["temp": 17]]
var myArray = ["Monday", "Tuesday", "Wed", "Thursday", "Friday", "Sat", "Sunday"]

let temps = test1.compactMap { $0["temp"] as? Int }

let finalArray: [[String: Int]] = zip(temps, myArray)
    .map { (temp, day) in [day: temp] }
print(finalArray)