2017-08-29 67 views
0

我想在我选择的一天之前删除所有日期,但不包括那一天,但我不能这样做。由于从字典中删除所有日期之前我选择的日期

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

使用Swift提供的结构来表示数据(在这种情况下,'Date'代替'NSDate'),除非有特定的原因需要使用其他版本。 – nathan

回答

1

你也可以完全避免使用DateFormatters并通过String值进行比较。在这种特定情况下,由于您提供的数据格式化(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 

正如大卫previusly评论说,他的解决办法是更通用的,但是这一次的速度要快得多,因为它不需要解析在每次迭代的日期。

0

Date符合Comparable协议,因此,如果使用<操作您选择的日期之前发生某一特定日期,您可以检查。所以它看起来是这样的:

var newDictionaryTotal = dictionaryTotal 
for (key, value) in dictionaryTotal 
{ 
    let date = formatter.date(from: key) 
    if date < theStart { 
     newDictionaryTotal.removeValue(forKey: key) 
    } 
} 
+0

虽然'date'和'theStart'都是可选的。 – nathan

+0

更新了答案 –

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命名约定,该命名约定是变量名称的lower-camelcase。只有在过滤器内使用强制展开才能100%确保所有密钥都具有相同的格式。

+1

或者只是使用String而不是解析日期。在这个特定的情况下(由于格式),字符串比较也会达到相同的结果。不知道什么更有效,日期解析或字符串比较。 – nathan

+0

你是对的,对于这种特殊格式甚至字符串比较都可以工作。然而,由于OP从DateFormatter开始,这是更通用的解决方案,我选择坚持下去。在性能方面,我不确定哪一个会更好,但是我猜想,因为数据集每天都有一个键值对,所以它不可能达到如此多的性能要素。 –

+1

'0.0131015833339916 s'(日期格式化程序解决方案)与'0.000600666666286997'(字符串比较) – nathan

相关问题