1

I recently changed some picker code in SwiftUI to use a CaseIterable Enum rather than an array of items.

Here is the enum:

enum ReturnTypes : String, CaseIterable {
    case Scaler
    case Vector
    case Matrix
}

Here is the picker code:

        NavigationView {
            Form {
                Picker("Return Type:", selection: $task.returnType) {
                    ForEach(ReturnTypes.allCases, id: \.self) { type in
                        Text(type.rawValue)
                    }
                }
            }
         }

When I previously had the data in an array and used

let returnTypes = ["Scaler", "Vector", "Matrix"]
...
                Picker("Return Type:", selection: $task.returnType) {
                    ForEach(0..<returnTypes.count, id: \.self) {
                        Text(returnTypes[$0])
                    }
                }

the current value of task.returnType was displayed on the picker line of the form next to the chevron. Using the enum, the task.returnType is NOT displayed next to the chevron and when I drill down to the picker selection view nothing is checked and even if I select an item, I still don't get anything displayed next to the chevron. Anyone else run into this issue?

Ferdinand Rios
  • 972
  • 6
  • 18

1 Answers1

2

The selection must be of the same type as picker data, not Text label, as on below working example. Tested with Xcode 11.4 / iOS 13.4.

demo

struct ContentView: View {
        @State private var returnType: ReturnTypes = .Scaler
        var body: some View {
        NavigationView {
            Form {
                Picker("Return Type:", selection: $returnType) {
                    ForEach(ReturnTypes.allCases, id: \.self) { type in
                        Text(type.rawValue)
                    }
                }
            }
         }
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690