Home > database >  Generic Enum as a Parameter for a Picker SwiftUI iOS
Generic Enum as a Parameter for a Picker SwiftUI iOS

Time:10-02

I am trying to create a entry field view that will accept any enum for a Picker (as long as that enum conforms to CaseIterable and String.

struct EntryFieldView<T: CaseIterable>: View where T.AllCases: RandomAccessCollection, T.AllCases.Element: Hashable & RawRepresentable, T.AllCases.Element.RawValue == String {
    @State var fieldTitle: String = ""
    @State var dropDownSelection: T
    @Binding var entry: String
    var body: some View {
        VStack(spacing: 0) {
            Group {
                if self.fieldTitle.isEmpty == false {
                    HStack {
                        Text(self.fieldTitle)
                            .font(.system(size: 10))
                        Spacer()
                    }
                }
                ZStack {
                    Rectangle()
                        .frame(height: 40)
                        .foregroundColor(.white)
                        .shadow(radius: 2)
                    HStack {
                        Picker("Test", selection: self.$entry) {
                            ForEach(self.dropDownSelection.allCases, id: \.self) { selection in
                                Text(selection.rawValue)
                            }
                        }
                    }
                    .padding([.leading, .trailing], 5)
                }
            }
            .padding(.bottom, 10)
        }
    }
}

And for example I have a simple list of countries:

enum Countries: String, CaseIterable {
    case UK = "United Kingdom"
    case USA = "United States of America"
    case ES = "Spain"
    case PL = "Poland"
    case DE = "Germany"
}

I get the error Static member 'allCases' cannot be used on instance of type 'T' with the suggestion Static member 'allCases' cannot be used on instance of type 'T'

If dropDownSelection is of Type T and T conforms to CaseIterable, why can't I use dropDownSelection.allCases, and why would it suggest I replace dropDownSelection with instance T?

Thanks

CodePudding user response:

allCases is a static member on the type T. dropDownSelection is a single case of that enum.

For example, let's remove the generic T and just your your example Countries. You could say Countries.allCases (note that Countries is a Type), but you would not do:

let country: Countries = .USA
let all = country.allCases // Error
  • Related