向后浏览字典以查找上次更新值的时间

时间:2018-09-26 17:00:48

标签: arrays swift

我有一个Dictionary数组,其中有两个感兴趣的关键对。一个密钥对是日期,另一个是“ 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的日期?

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题,它使用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