Search code examples
swiftswiftuilocaleregion

List all Locale Identifiers and corresponding region text Swiftui


I would like to generate a list of all Locale identifiers for the user to select as a default. Similar to selecting the region in the standard settings.

Thus I would like to generate a list that would contain e.g. "Australia", "Austria", "Azerbaijan", ... ,"Yemen", "Zambia", "Zimbabwe". If the user selects "Australia" I would like to return en_AU.

So need to identify the property under Locale that can be used and how to iterate through it.

Currently, just trying to see if I can return the text e.g. "Australia":

Text(Locale.localizedString(Locale.init(identifier: Locale.availableIdentifiers[0].description)))

However returning error:

Closure containing control flow statement cannot be used with function builder 'ViewBuilder'

Thank you


Solution

  • Seems like you are looking for the name of each identifier. You can get those from the NSLocale like:

    Locale.availableIdentifiers.map {
        (id: $0, name: (NSLocale.current as NSLocale).displayName(forKey: .languageCode, value: $0) ?? "-")
    }
    

    So you can rise them as you like. For example, showing them in a list:

    struct ContentView: View {
        let localeSheet: [(id: String, name: String)] = {
            Locale.availableIdentifiers.map {
                (id: $0, name: (NSLocale.current as NSLocale).displayName(forKey: .languageCode, value: $0) ?? "-")
            }.sorted { $0.name < $1.name }
        }()
    
        var body: some View {
            List(localeSheet, id: \.id) {
                Text($0.name)
                Spacer()
                Text($0.id)
            }
        }
    }