我是新来的,所以如果我错误地格式化了这个(也是swift的新手),请更正我,但基本上我想要做的是采用一系列日期和数字,如果有任何日期是同样将数字合并为一个条目。
所以这个
//This is how i format the data after i pull it from core data
var dateAndEntry = [(String, Double)]
//i've split them into two seperate arrays for sorting, but I feel like theres a better way i don't know
var dates = ["01/01/2016", "02/01/2016", "02/01/2016", "04/01/2016", "05/01/2016", "06/01/2016","07/01/2016","07/01/2016"]
var entries = [-14,2,8,9,-1,8,25,6]
变成这个
var dates = ["01/01/2016", "02/01/2016", "04/01/2016", "05/01/2016", "06/01/2016","07/01/2016"]
var entries = [-14,10,9,-1,8,19]
我试过这样做但我只能得到它以便它创建一个只包含新值的新数组,而不是允许我获取重复值,组合,插入索引然后删除原始条目这两个阵列。
func combineDuplicates(dates: [String]) -> [String]{
var output: [String] = []
var checked = Set<String>()
for date in dates {
if !checked.contains(date) {
checked.insert(date)
output.append(date)
}
}
print(output)
return output
}
let sorted = combineDuplicates(dates)
print(sorted)
是的,我已经在谷歌和这里寻找答案,但没有找到任何答案。
任何有关我可能错过的其他问题或来源的解决方案,解释,帮助,指示或参考都将不胜感激。
答案 0 :(得分:3)
这将为您提供一个字典,其中包含日期和值,每个日期的条目总和:
dates.enumerate().reduce([String:Int]()) { dict, item in
var dict = dict
dict[item.1] = (dict[item.1] ?? 0) + entries[item.0]
return dict
}
// ["06/01/2016": 8, "04/01/2016": 9, "01/01/2016": -14, "05/01/2016": -1, "07/01/2016": 31, "02/01/2016": 10]