UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Form Picker Error: requires that X conform to hashable

Forums > Swift

Within a Form I have a "Your Current Department" Picker for the app user to select their department of employment (Sales, Management, etc.). This Picker's selection pulls from the viewModel.

Here is a link to the code on GitHub.

The following two errors on the ProfileFormView inhibit compilation:

  1. "Generic struct 'Picker' requires that 'Department' conform to 'Hashable'"

  2. "Referencing initializer 'init(_:selection:content:)' on 'Picker' requires that 'Department' conform to 'Hashable'"

struct ProfileFormView: View {

    @Environment(\.colorScheme) var colorScheme
    @Binding var tabSelection: Int
    @EnvironmentObject var vm: EmployeeViewModel
    let hoursWorked = 120...180
    let currentDept = ["Sales","Management","Senior Management","Hospitality","Sanitation","Other"]

    var body: some View {
        NavigationView {
            VStack {
                Form {
                    Section(header: Text("Personal Information:")
                        .foregroundColor(colorScheme == .dark ? Color.white: Color.black)
                        .font(.body)
                        .bold()) {
                            Picker("Hours per Month", selection: $vm.userData.monthlyHoursWorked) {
                                ForEach(hoursWorked, id: \.self) {
                                    Text("\($0)")
                                }}
                            //error is below
                            Picker("Your Current Department", selection: $vm.userData.department) {
                                ForEach(currentDept, id: \.self) {
                                    Text ($0)
                                }
                            }
                        }
                }
            }
            .navigationTitle("Employee Information")
            .toolbar {
                NavigationLink(destination: PayRateView(
                    depts: DeptList.deptList), label: {Text("Pay Charts")
                    })
            }
        }
        .accentColor(Color(.label))
        .navigationViewStyle(StackNavigationViewStyle())
    }
}

The "Department" is a variable within the Employee model:

struct Employee: Identifiable {
    var id = UUID()
    let name: String
    var birthdate: Date
    var hiredate: Date
    var retirementAge: Int
    var department: Department
    var monthlyHoursWorked: Int
    var regularPayRateIncreases: Bool
    var regularPayRateIncreasePercentage: Int
    var regularPayRateIncreaseYearInterval: Int

    private(set) var employmentHistory: [Department]

    init(_ name: String,
         birthdate: Date,
         hiredate: Date,
         retirementAge: Int,
         department: Department = .other("Employee"),
         monthlyHoursWorked: Int,
         regularPayRateIncreases: Bool,
         regularPayRateIncreasePercentage: Int,
         regularPayRateIncreaseYearInterval: Int)
    {
        self.name = name
        self.birthdate = birthdate
        self.hiredate = hiredate
        self.retirementAge = retirementAge
        self.department = department
        self.monthlyHoursWorked = monthlyHoursWorked
        self.regularPayRateIncreases = regularPayRateIncreases
        self.regularPayRateIncreasePercentage = regularPayRateIncreasePercentage
        self.regularPayRateIncreaseYearInterval = regularPayRateIncreaseYearInterval
        self.employmentHistory = []
    }
}

If I add Hashable to this struct, I get the following two errors:

  1. "Type 'Employee' does not conform to protocol 'Equatable' "

  2. "Type 'Employee' does not conform to protocol 'Hashable' "

2      

Try to add those methods in your struct like so

    static func ==(lhs: Employee, rhs: Employee) -> Bool {
        return lhs.id == rhs.id
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }

and add protocols to your struct Employee accordingly.

struct Employee: Identifiable, Equatable, Hashable

2      

@ygeras

Thank you!

Your suggestions removed the errors in my model, but I still have the two errors in the ProfileFormView:

"Generic struct 'Picker' requires that 'Department' conform to 'Hashable'"

"Referencing initializer 'init(_:selection:content:)' on 'Picker' requires that 'Department' conform to 'Hashable'"

2      

As per Hashable protocol you have to do as follows:

  • For a struct, all its stored properties must conform to Hashable.
  • For an enum, all its associated values must conform to Hashable. (An enum without associated values has Hashable conformance even without the declaration.)

You Department type is enum. But the point is that it is a mixture of associated values and cases without them. On the other hand I found such solution workable

hasher.combine(value) // combine with associated value, if it's not Hashable map it to some Hashable type and then combine result

So theoretically this might sovle your problem ->

extension Department: Hashable {
    func hash(into hasher: inout Hasher) {
        switch self {
        case .sales:
            hasher.combine("Sales")
        case .management:
            hasher.combine("Management")
        case .seniorManagement:
            hasher.combine("Senior Management")
        case .other(let value):
            hasher.combine(value)
        }
    }
}

At least in playgrounds it generates hashValue accordingly.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.