swift - How do you sort dates in a dictionary? -
i having trouble trying sort following dictionary, printed in oldest date first order when printed.
var daytotaldictest: [string:int] = [ "04-09-2015" : 4, "04-10-2015" : 6, "04-07-2015" : 8, "03-28-2015" : 10, "12-10-2014" : 12, "12-10-2015" : 12, ]
edit/update: xcode 8.2.1 • swift 3.0.2
extension string { static let shortdateus: dateformatter = { let formatter = dateformatter() formatter.calendar = calendar(identifier: .iso8601) formatter.locale = locale(identifier: "en_us_posix") formatter.datestyle = .short return formatter }() var shortdateus: date? { return string.shortdateus.date(from: self) } } let daytotaldictest: [string:int] = [ "04-09-2015" : 4, "04-10-2015" : 6, "04-07-2015" : 8, "03-28-2015" : 10, "12-10-2014" : 12, "12-10-2015" : 12] let myarrayoftuples = daytotaldictest.sorted{ guard let d1 = $0.key.shortdateus, let d2 = $1.key.shortdateus else { return false } return d1 < d2 } print(myarrayoftuples) // [("12-10-2014", 12), ("03-28-2015", 10), ("04-07-2015", 8), ("04-09-2015", 4), ("04-10-2015", 6), ("12-10-2015", 12)]\n" tuple in myarrayoftuples { print(tuple) }