How can I remove duplicates from a Picker

Hi,

I created a Picker using an Enum Description Value, however, when rendering, if two cases give the same return the picker shows the value twice. Is there any way to clean the duplicate up?

I'll leave an example of my enum and my Picker code and a capture of the rendered Picker

// My Enum
enum Race: String, CaseIterable {

case Ainur, Balrog, Dragon, Dragons, Dwarf, Dwarves, Eagle, Eagles
   
  var description: String {
     
    switch self {
       
    case .Ainur:
      return "Ainur"
       
    case .Balrog:
      return "Balrog"
       
    case .Dwarf, .Dwarves:
      return "Dwarf"
       
    case .Eagle, .Eagles:
      return "Eagles"
}
       
// My Picker

             Picker("Filter by Race", selection: $raceSelection) {
               
              ForEach (Race.allCases, id: \.self, content: { race in
                 
                Text(race.description)
                  .tag(race.description)
              })
            }

Thanks!

Make an array of the unique enum descriptions, and use that in your ForEach.

You could write a method to calculate this...
...or just do it manually in your Race enum

e.g. (in Race enum)

static var uniqueValues: [Race] { [.Ainur, .Balrog, .Dwarf, .Eagle] }

then (in Picker)

ForEach (Race.uniqueValues, id: \.self, content: { race in
Accepted Answer

This should not compile, as you forgot Dragon(s)

You can compute the unique labels:

enum Race: String, CaseIterable {
    
    case Ainur, Balrog, Dragon, Dragons, Dwarf, Dwarves, Eagle, Eagles
    
    var description: String {
        
        switch self {
            
        case .Ainur:
            return "Ainur"
            
        case .Balrog:
            return "Balrog"
            
        case .Dwarf, .Dwarves:
            return "Dwarf"
            
        case .Eagle, .Eagles:
            return "Eagles"
            
        case .Dragon, .Dragons: // NEED this case
            return "Dragons"
        }
    }

    static var uniqueDescriptions : [String] {
        var currentDescriptions : [String] = []
        for race in Race.allCases {
            if !currentDescriptions.contains(race.description) {
                currentDescriptions.append(race.description)
            }
        }
        return currentDescriptions
    }

}

print(Race.uniqueDescriptions)

Gives

["Ainur", "Balrog", "Dragons", "Dwarf", "Eagles"]

So Picker code:

             Picker("Filter by Race", selection: $raceSelection) {
               
              ForEach (Race.uniqueDescriptions, id: \.self, content: { race in
                 
                Text(race.description)
                  .tag(race.description)
              })
            }
How can I remove duplicates from a Picker
 
 
Q