UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Best way to group String array by first character and show in Table View as groups?

Forums > Swift

Hello all,

I am working on allowing user to select country from a list. I can get list of all countries from iOS with Locale.isoRegionCodes and then getting localized name for users locale with localizedString(forRegionCode:. I also have the sorting based on current Locale working pretty great.

But I got kind of stuck on creating groups by first letter and showing those in Table View. I cannot come up with something elegant..

let groups = Dictionary(grouping: countries) { (country) -> Character in
            return country.first!
}

This will create groups based on country's first letter but it is not something that can be readily shown in Table View because I need to access those groups based on section index..

Thanks for help!

3      

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.)

5      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.