Reputation: 6414
I'm trying to sort a dictionary in Swift by keys. My keys are following a custom pattern and I'm unable to figure out a proper way to sort the dictionary.
I simplified my task using this dict
of names and seasons:
var dict = [
"Summer 14": [["Peter"], ["Karl"], ["Jeff"], ["Sandra"]],
"Winter 14/15": [["Gil"], ["Monica"]],
"Winter 13/14": [["Sandra"], ["Anna"], ["Bert"]]
]
The basic sorting options like Array(dict.keys).sorted(<)
don't apply properly.
My desired result is a sorted dictionary with keys in this order: Winter 13/14 < Summer 14 < Winter 14/15
.
Thanks in advance.
Upvotes: 1
Views: 1275
Reputation: 131418
It seems to me your main challenge is a way to sort your season strings. The fact that you want to sort an array of dictionary keys is incidental.
I would suggest creating a global function valueForSeason that takes a string as input. It would return a double representing the season: The starting year value as the integer part, plus 0.0 for summer and 0.5 for winter. Return 0.0 for a malformed season string so those float to the top.
Then you could pull out your dictionary keys into an array and sort them by valueForSeason:
var keys = dict.keys
keys.sort()
{
$0.valueForSeason() < $1.valueForSeason()
}
Note that you've got a Y2K bug lurking in your data format that you really can't fix. You're using 2 character years, and 99 most likely represents 1999, but it would sort after 14. You can play games like assuming dates after '50 are in the 1900's and dates before '50 are in the 2000's, but that approach is error-prone. You'd be much better off changing your string format to " YYYY" (e.g. "Summer 2014" and "Winter 2014/2015")
Upvotes: 1