Let's say you have the following Objective-C code with NSDictionary and NSArray :
NSDictionary *partsOfNovel = @{@"Part 1" : @[@"Chapter X:1", @"Chapter X:2", @"Chapter X:3"], @"Part 4" : @[@"Chapter X:1", @"Chapter X:2"], @"Part 3" : @[@"Chapter X:1"]}; NSArray *partsSectionTitles = [[partsOfNovel allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; NSLog(@"%@", partsSectionTitles);
With this code, your console will print:
"Part 1", "Part 3", "Part 4"
With Swift, you can get Dictionary keys and put them in Array as follows:
let partsOfNovel = [ "Part 1" : ["Chapter X:1", "Chapter X:2", "Chapter X:3"], "Part 4" : ["Chapter X:1", "Chapter X:2"], "Part 3" : ["Chapter X:1"]] let nonOrderedPartsSectionTitles = partsOfNovel.keys.array
Then you can apply sorting on this Array and print the result as follows:
let partsSectionTitles = nonOrderedPartsSectionTitles.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending } println(partsSectionTitles) //[Part 1, Part 3, Part 4]
But all this can be done using Swift in short form (tested on the Playground):
let partsOfNovel = [ "Part 1" : ["Chapter X:1", "Chapter X:2", "Chapter X:3"], "Part 4" : ["Chapter X:1", "Chapter X:2"], "Part 3" : ["Chapter X:1"]] let partsSectionTitles = partsOfNovel.keys.array.sorted { $0.0 < $1.0 } println(partsSectionTitles) //[Part 1, Part 3, Part 4]