SwiftUI Country Picker - Show Country Name but store Country ID

Viewed 1647

UPDATE: I updated the code to my previous semi-working solution because there were multiple answers, but none answered the question the way I need it to work.

Also, note that I need United States at the top of the picker, even if it appears again in the alphabetical country listing.


I am trying to create a picker that displays a country name, and depending on what country is selected, stores the corresponding country id. This way the user sees the name of the country but I can pass only the country id into my database.

The code I have so far shows the list of country names, and stores that country name in the selectedCountry variable. It also updates the text element in the HStack properly.

The only thing that is not working is storing the corresponding countryId.

I am using SwiftUI with the latest Swift 5 and XCode 13.1.

Here's what I've got so far:

    import SwiftUI
        
            struct Country: View {
             
                @State private var selectedCountry = ""
                @State private var selectedCountryId = ""
             
                let countryId = Locale.isoRegionCodes
                let countryArray = Locale.isoRegionCodes.compactMap { Locale.current.localizedString(forRegionCode: $0) }
            
                var body: some view {
    
                    HStack {
                        Text("Country:")
                            .font(.system(size: 17))
                        Spacer()
                                    
                        Text("")
                        if selectedCountry != "" {
                            Text("\(selectedCountry)")
                                .font(.system(size: 17))
                                .foregroundColor(Color("WhiteText"))
                        } else {
                              Text("Select Country")
                                  .font(.system(size: 17))
                                  .foregroundColor(Color("GrayText"))
                        }
                                    
                     } // End HStack
                                
                     .onTapGesture {
                         self.showsCountryPicker.toggle()
                     }
             
                Picker("Country", selection: $selectedCountry) {
                        ForEach(countryArray, id: \.self) {
                            Text($0)
                            }
                        }
                        .pickerStyle(WheelPickerStyle())
                        .padding()
                        .labelsHidden()
                     }
}
}

I'm sure it's completely the wrong way to do this, so don't worry so much about correcting my code. I'd really just love to know how to do this, because I'll also need to implement the same thing when it comes to selecting a US State (i.e. show the full name of the State but store the abbreviation).

Also, there is much more to the body view, but I've stripped down the code here just to show this specific issue.

Thanks in advance!

5 Answers

The Picker documentation says to use the tag modifier on each Text to control what the Picker stores in its selection.

There's no reason to store an array of country names if you just want to store the selected country code. And you should use SwiftUI's Environment to get the current Locale, so that your view will be redrawn if the user changes her locale.

import SwiftUI
import PlaygroundSupport

struct CountryPicker: View {
    @Binding var countryId: String
    @Environment(\.locale) var locale
    
    var body: some View {
        Picker("", selection: $countryId) {
            ForEach(Locale.isoRegionCodes, id: \.self) { iso in
                Text(locale.localizedString(forRegionCode: iso)!)
                    .tag(iso)
            }
        }
    }
}

struct Test: View {
    @State var countryId: String = ""
    
    var body: some View {
        VStack {
            CountryPicker(countryId: $countryId)
            Text("You picked \(countryId).")
        }
        .padding()
    }
}

PlaygroundPage.current.setLiveView(Test())

I appreciate all the assistance, but I got it all working the way I needed it to. For this I am storing only the Country ID, which is all I need, but translating that ID into the country name for the text element in the HStack.

Here's the answer:

import SwiftUI

// Struct to store the country name and ID

fileprivate struct Country {
    var id: String
    var name: String
}

// Function to put United States at the top of the list

fileprivate func getLocales() -> [Country] {
    let locales = Locale.isoRegionCodes
        .filter { $0 != "United States"}
        .compactMap { Country(id: $0, name: Locale.current.localizedString(forRegionCode: $0) ?? $0)}
    return [Country(id: "US", name: Locale.current.localizedString(forRegionCode: "US") ?? "United States")] + locales
}

struct Test: view {

// selectedCountry stores the countryID (i.e. US)
    @State private var selectedCountry: String = ""
    
 // Main UI
    
    var body: some View {

        HStack {
            Text("Country:")
                .font(.system(size: 17))
            Spacer()
                                
            Text("")
            if selectedCountry != "" {
                Text(Locale.current.localizedString(forRegionCode: selectedCountry) ?? selectedCountry)
                    .font(.system(size: 17))
                    .foregroundColor(Color("WhiteText"))
             } else {
                   Text("Select Country")
                       .font(.system(size: 17))
                       .foregroundColor(Color("GrayText"))
               }
                                
             } // End HStack

             Picker("Country", selection: $selectedCountry) {
                 ForEach(getLocales(), id: \.id) { country in
                 Text(country.name).tag(country.id)
                 }
             }

}
}

This my friend is where dictionaries come in handy. A dictionary has two parts Key and Value or in swift terms ["Key":"Value"] There are three things to note about a dictionary.

  • #1, all key-value-pairs MUST be the same type, for example, [32:"String", 33: "String"] Which is important to remember.
  • #2, it does NOT guarantee order.
  • #3, It can only contain unique keys.

How does this apply to your problem? Well, it has to do with the type of data that you have. Currently you have 2 separate arrays, one with the Country, and one with the Codes. You can combine them into the dictionary and ensure that they are always together, referencing the value from the key, or searching for the value, to get a key or multiple keys. That previous sentence is important to pay attention to, though not for your case, you're guaranteed to only get one value for one key, but you can get multiple keys from one value. In your case you have a unique country, and unique ID.

var countries = ["USA": 9999,
                 "UK": 9998,
                 "Canada": 9997] // Etc..

Getting a value from a dictionary is even easier, but works similar to an array. You sub-script it. For example:

var canadaID= countries["Canada"]

Now it gets trickier getting a key from a value because you have to iterate over the whole dictionary to grab it. It's also possible that there are duplicate values, meaning you could technically get back an array of "Keys". In this example, I grabbed only the first found value. Again, remember that the order is not guaranteed and if you have multiple of the same value you may get the incorrect key.

var countryID = 9998

if let key = countries.first(where: { $0.value == someValue })?.key {
    print(key)
}

From here it becomes trivial to store it.

func storeCountryIDFromKey(country: String) {
     let countryId = countries[country]
     // Store your ID.
}

What if my order is important??!??

This could be important for your case as you might want to display the countries in alphabetical order. To do that simply map the keys to an array and sort, as is tradition.

let keys: [String] = countries.map{String($0.key) }

Solution

This is a working solution. I'll leave it up to you to sort the arrays and link the data where you need it to go. You could use onChange(...) or even a Button(..) to handle the update, however your ID is the selectedCountry in this example.

struct FirstView: View {
    @State var countries = ["US": 1,
                            "UK": 2,
                            "Canada": 4]
    
    @State var selectedCountry = 1
    
    var body: some View {
        VStack {
            Picker("Country", selection: $selectedCountry) {
                let countriesArray = countries.keys.map({$0})
                
                ForEach(countriesArray, id: \.self ) { country in
                    Text(country).tag(countries[country]!)
                }
            }.pickerStyle(.wheel)
            
            Text("\(selectedCountry)")
        }
    }
}

Additional Reading

There is a concept in programming called Big-O notation typically expressed as O(n) or pronounced O-of-N. Which is the way that we describe time and space complexities. It's a great skill to learn if you want to become a great developer as it has to do with Data Structures and Algorithms. To make more sense of this, as it applies to your question, having two separate arrays to loop over vs one dictionary effectively takes 2x as long to accomplish with the double arrays. Furthermore it doubles the space complexity. Combining both into one Dictionary reduces your performance overhead by 1/2 which is a huge performance gain. With a small data-set such as countries, which there are a finite amount, it doesn't really matter; However, if you start working with massive datasets then suddenly 1/2 faster is a substantial performance boost.

Without digging too much into it, and to simply get your wheels spinning, every time you make a variable, or the compiler does that for you, that increases space complexity. Every time you run a line of code, or loop over a line of code, that increases the time complexity. Always, and I mean always, try your best to reduce that overhead. It'll force you to think outside the box and in turn, you'll learn better practices.

I would just do something simple like this:

struct Country: Identifiable, Hashable {
    let id: String
    let name: String
}

struct CountryView: View {
    let countries = Locale.isoRegionCodes.compactMap{
        Country(id: $0, name: Locale.current.localizedString(forRegionCode: $0)!) }
    
    @State var selectedCountry: Country?
    
    var body: some View {
        Picker("Country", selection: $selectedCountry) {
            ForEach(countries) {
                Text($0.name).tag(Optional($0))
            }
        }.pickerStyle(.wheel)
            .onChange(of: selectedCountry) { selected in
                if let cntry = selected {
                    print("--> store country id: \(cntry.id)")
                }
            }
    }
}

If you want to sort the countries, use this:

ForEach(countries.sorted(by: { $0.name < $1.name })) { ... }

For creating and sorting the array of countries, this is my suggestion

// create a Country struct

struct Country:Equatable{
    let code:String
    let name:String
}

/** creating the array by first getting the 
  the codes and then sorting it, bubbling US to the top
[Sorted by][1]
**/

    let countries = Locale.isoRegionCodes.compactMap 
    {  Country(code:$0,name:Locale.current.localizedString(forRegionCode: $0) ?? "")
        }.sorted{
                switch ($0,$1){
                case ($0,$1) where $0.code == "US":
                    return true
                case ($0,$1) where $1.code == "US":
                    return false
                default:
                    return $0.name<$1.name
                }
        }

You can now store your selection and get the code and name or whatever you wish to by changing the struct as per your needs

Related