Swift 从字典中删除我选择的日期之前的所有日期

Swift 从字典中删除我选择的日期之前的所有日期,swift,Swift,我想删除我选择的日期之前的所有日期,不包括那天,但我不能这样做。谢谢 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() formatt

我想删除我选择的日期之前的所有日期,不包括那天,但我不能这样做。谢谢

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)

}
日期符合可比协议,因此您可以使用字典上的过滤器检查给定日期是否出现在所选日期之前

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%确定所有键的格式都相同。

您还可以完全避免使用日期格式化程序,并按字符串值进行比较。在这种特定情况下,由于您提供的数据格式为yyyy-MM-dd,因此它将起作用


正如Dávid之前所评论的,他的解决方案更通用,但这个解决方案速度更快,因为它不需要在每次迭代中解析日期。

在这种情况下,使用Swift提供的结构来表示数据日期,而不是NSDate,除非有特殊原因,否则您需要使用其他版本。日期和开始都是可选的。或者只使用字符串而不是解析日期。在这种特定情况下,由于格式的原因,字符串比较也将获得相同的结果。不过,不确定什么更有效,日期解析还是字符串比较。没错,对于这种特殊格式,甚至字符串比较都可以。然而,由于OP是从DateFormatter开始的,而DateFormatter是更通用的解决方案,所以我选择坚持使用它。就性能而言,我不确定哪一个更好,但我猜,由于数据集每天有一个键值对,因此不太可能遇到如此多的元素,性能才真正重要。0.013105833339916 s日期格式化程序解决方案与0.0006006666286997字符串比较
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
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