Couple of different semi-elegant ways I would consider. One would be to simply create a separate instance variable to hold your section mapping from indexes to letters:
let sectionIndexes = groups.keys.sorted() // Array<Character>: ["A", "B", "C"...]
Then you can get your section count by sectionIndexes.count
, and when asked for the countries in a section i
, call groups[sectionIndexes[i]]!
.
Or, you could combine it all in to one array that holds tuples of your section letters and countries:
let sections = Dictionary(grouping: countries) { (country) -> Character in
return country.first!
}
.map { (key: Character, value: [String]) -> (letter: Character, countries: [String]) in
(letter: key, countries: value)
}
.sorted { (left, right) -> Bool in
left.letter < right.letter
}
// [(letter: "A", countries: ["Afghanistan", "Albania", ...]), (letter: "B", countries: ["Bahamas", "Bahrain", ...])]
Section count would be sections.count
, and you can get the letter and countries of each section i
by sections[i].letter
and sections[i].countries
.
(You could also map to CountrySection
structs with similar properties if tuples aren't your bag.)