我有一个字典数组,其中有两个感兴趣的键对。一对 key 是日期,另一对是“investpercent”,其值经常变化。我想查找 investpercent
的最后更新日期。所以,请考虑:
var importedRecords = [
["low": "1.0", "date": "2018-04-25", "objective": "2.0", "savings": "2.0", "high": "2.0", "expenses": "1.0", "investpercent": "3.0"],
["low": "1.0", "date": "2018-05-25", "objective": "2.0", "savings": "2.0", "high": "2.0", "expenses": "1.0", "investpercent": "3.0"],
["low": "1.0", "date": "2018-06-25", "objective": "2.0", "savings": "2.0", "high": "2.0", "expenses": "1.0", "investpercent": "4.0"],
["low": "1.0", "date": "2018-07-25", "objective": "2.0", "savings": "2.0", "high": "2.0", "expenses": "1.0", "investpercent": "4.0"],
["low": "1.0", "date": "2018-08-25", "objective": "2.0", "savings": "2.0", "high": "2.0", "expenses": "1.0", "investpercent": "5.0"],
["low": "2", "date": "2018-09-26", "objective": "2.0", "savings": "2.0", "high": "4", "expenses": "1.0", "investpercent": "5.0"]
]
现在,请注意 investpercent
最后一次更改是在“2018-08-25”,我感兴趣的值是“5.0”。我的想法是这样的:
var lastentry = importedRecords.suffix(1)
var lastdate: String = ""
for record in importedRecords {
if record["investpercent"] == lastentry["investpercent"] {
lastdate = record["date"]
}
}
但我无法尝试将该数组切片转换为合适的字典。
- 如何浏览此数组以检测上次更新
investpercent
的日期?
最佳答案
这应该可以解决问题,它使用 zip
:
let reversedRecords = importedRecords.reversed()
let zipped = zip(reversedRecords.dropFirst(), reversedRecords)
if let twoDictionaries = zipped.first(where: {$0["investpercent"] != $1["investpercent"]}),
let date = twoDictionaries.1["date"] {
print(date)
}
它打印 2018-08-25
关于arrays - 向后浏览词典以查找上次更新值的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52522797/