Dictionaries are not sorted, so you need to convert them to an array. The map function can do this for you. In addition, the rows cannot be sorted as intended, so you need to either rebuild the row in yyyy-MM-dd format or convert it to a date.
But as soon as you do this, you can sort the array. For example, using functional programming in Swift, you can do something like the following, which uses map to convert the dictionary into an array of tuples, and then uses sorted to sort them, using NSDateFormatter to convert strings to dates:
var dayTotalDictionary: [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 formatter = NSDateFormatter() formatter.dateFormat = "MM-dd-yyyy" let dayTotalArray = map(dayTotalDictionary) { ($0, $1) } .sorted() { formatter.dateFromString($0.0)!.compare(formatter.dateFromString($1.0)!) == .OrderedAscending }
Although this has some simplicity, it is probably a bit inefficient, calling dateFromString more than we need. So, I probably would have a map function to add an NSDate object to an array of tuples, and then sorted can use an existing NSDate object:
let dayTotalArray = map(dayTotalDictionary) { (formatter.dateFromString($0)!, $0, $1) } // in Swift 2.0, use `dayTotalDictionary.map()` .sorted() { ($0.0 as NSDate).compare($1.0 as NSDate) == .OrderedAscending } // in Swift 2.0, use `sort` .map() { (_, dateString, dayTotal) in (dateString, dayTotal) }
This final map pulls out the NSDate object, but obviously you don't need to do this if you support NSDate in a tuple.