2017-08-29 63 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

相關問題