Swift - 类型 '' 不符合协议 'Hashable'

Luk*_*ers 4 swift

所以我有这个结构:

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

但是我在说Type 'ListAction' does not conform to protocol 'Hashable'.

如果我删除定义action常量的行,我可以摆脱错误,但我不想永久删除该行。

我正在使用 Swift 5.1。

bba*_*art 12

Hashable通过覆盖hash(into:)和调用combine所有相关属性来提供您自己的实现。

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
}
Run Code Online (Sandbox Code Playgroud)