Reputation: 45
I have a dictionary in Swift that looks somewhat like this:
[
"1": [
"start": //An NSDate,
"end": //An NSDate,
"id": "1",
"other non relevant items": "below",
]
]
And I want to sort it by the start date, with the key "start"
. I've seen the article on sorting dictionaries by value here but how would I do this with NSDates? Could you also give an example?
Upvotes: 2
Views: 1634
Reputation: 40963
Note, you cannot sort a dictionary, except in the sense that you can sort any sequence, which turns it into an array of key/value pairs.
You haven’t said, but assuming your dictionary is of type [String:[String:AnyObject]]
, you could sort it (to get a result of an array of pairs, i.e. [(String,[String:AnyObject])]
) like this:
let sorted = d.sort { lhs,rhs in
let l = lhs.1["start"] as? NSDate
let r = rhs.1["start"] as? NSDate
return l < r
}
This is assuming you’ve also enhanced NSDate
to have a <
operator like so:
extension NSDate: Comparable { }
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.isEqualToDate(rhs)
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedAscending
}
Depending on what the actual type of your dictionary is, this might need some more type coercion.
If you don’t want the key in the sorted array (since it’s just a dupe of the ID), just sort the values:
let sorted = d.values.sort { lhs, rhs in
let l = lhs["start"] as? NSDate
let r = rhs["start"] as? NSDate
return l < r
}
That said, I’d suggest instead of using a dictionary for anything more than the most basic of manipulation, that instead you write a custom struct and stash your data in that, this will make operations like this much simpler.
Upvotes: 3