Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Type '' does not conform to protocol 'Hashable'

Tags:

swift

So I have this struct:

struct ListAction: Hashable {
    let label: String
    let action: (() -> Void)? = nil
    let command: Command? = nil
}

But I get an error on the line it's declared on saying Type 'ListAction' does not conform to protocol 'Hashable'.

I can get rid of the error if I remove the line defining the action constant but I don't want to remove that line permanently.

I'm using Swift 5.1.

like image 800
Luke Chambers Avatar asked Dec 11 '22 01:12

Luke Chambers


1 Answers

Supply your own implementation for Hashable by overriding hash(into:) and call combine on all the relevant properties.

struct ListAction: Hashable {
    static func == (lhs: ListAction, rhs: ListAction) -> Bool {
        return lhs.label == rhs.label && lhs.command == rhs.command
    }

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

    let label: String
    let action: (() -> Void)? = nil
    let command: Command? = nil
}
like image 154
bbarnhart Avatar answered Dec 12 '22 15:12

bbarnhart