我想在我选择的那天之前删除所有日期,不包括那天,但我不能这样做。感谢
var dictionaryTotal: [String:String] = ["2017 01 01":"153.23", "2017 01 02":"162.45", "2017 01 04":"143.65", "2017 01 05":"140.78", "2017 01 06":"150.23"]
let date = NSDate()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy MM dd"
formatter.timeZone = Calendar.current.timeZone
formatter.locale = Calendar.current.locale
let TheStart = formatter.date(from: "2017 01 04")
for (key, value) in dictionaryTotal {
var ConvertDates = formatter.date(from: key)
}
答案 0 :(得分:1)
您也可以完全避免使用DateFormatters并按字符串值进行比较。在这种特定情况下,由于您提供的数据格式化(yyyy MM dd
),它将起作用。
let startDate = "2017 01 04"
let filteredDictionary = dictionaryTotal.filter({ (key, _) in key >= startDate })
print(filteredDictionary) //contains key value pairs for the keys 2017 01 04, 01 05 and 01 06
正如Dávid所评论的那样,他的解决方案更通用,但是这个解决方案要快得多,因为它不需要在每次迭代时解析Date。
答案 1 :(得分:0)
Date
符合Comparable
协议,因此您可以使用<
运算符检查指定日期是否在您选择的日期之前。所以它看起来像这样:
var newDictionaryTotal = dictionaryTotal
for (key, value) in dictionaryTotal
{
let date = formatter.date(from: key)
if date < theStart {
newDictionaryTotal.removeValue(forKey: key)
}
}
答案 2 :(得分:0)
您可以在词典上使用filter
。
var dictionaryTotal: [String:String] = ["2017 01 01":"153.23", "2017 01 02":"162.45", "2017 01 04":"143.65", "2017 01 05":"140.78", "2017 01 06":"150.23"]
let formatter = DateFormatter()
formatter.dateFormat = "yyyy MM dd"
formatter.timeZone = Calendar.current.timeZone
formatter.locale = Calendar.current.locale
guard let startDate = formatter.date(from: "2017 01 04") else {fatalError()}
let filteredDictionary = dictionaryTotal.filter({ (key, value) in formatter.date(from: key)! >= startDate})
print(filteredDictionary) //contains key value pairs for the keys 2017 01 04, 01 05 and 01 06
还要确保符合Swift命名约定,即变量名称的较低值。只有在过滤器内部使用力展开才能100%确保所有按键具有相同的格式。