Reading time: 1 min

This recipe shows how to implement a country picker list in SwiftUI. The list can be constructed entirely programmatically, without the need for additional data.

The end result looks like this:

preview

There are three steps to this recipe:

#1 Get the list of all countries

You can easily get the list of all the country codes available on your system with NSLocale.isoCountryCodes.

#2 Get Unicode flag symbol for country code

There's a magic function that does this:

func countryFlag(_ countryCode: String) -> String {
  String(String.UnicodeScalarView(countryCode.unicodeScalars.compactMap {
    UnicodeScalar(127397 + $0.value)
  }))
}

#3 Get country name from country code

You can get the name of a country for any locale using Locale's localizedString(forRegionCode:) method.

Full code

Putting it all together, here's the code for constructing a list of all available countries, with their flags, names and country codes:

func countryFlag(_ countryCode: String) -> String {
  String(String.UnicodeScalarView(countryCode.unicodeScalars.compactMap {
    UnicodeScalar(127397 + $0.value)
  }))
}

struct CountryListTest: View {
  var body: some View {
    List(NSLocale.isoCountryCodes, id: \.self) { countryCode in
      HStack {
        Text(countryFlag(countryCode))
        Text(Locale.current.localizedString(forRegionCode: countryCode) ?? "")
        Spacer()
        Text(countryCode)
      }
    }
  }
}

Next Post Previous Post