简体   繁体   中英

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

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.

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
}

The struct needs a unique identifier to conform to Hashable. You can simply add a UID to your struct and then add a hash function as a comparison function to make the comparison.

struct ListAction: Codable, Hashable {
    var uid = UUID().uuidString
    let label: String
    let action: (() -> Void)? = nil
    let command: Command? = nil
    
    static func == (lhs: Self, rhs: Self) -> Bool {
        return lhs.uid == rhs.uid
    }
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(uid)
    }
    
}

you can add that those two functions and and var uid to any struct you have problems making Hashable.

It's a good practice to add extensions to your structs that require protocol functions like hash.

struct ListAction {
var uid = UUID().uuidString // add this 
    let label: String
    let action: (() -> Void)? = nil
    let command: Command? = nil
}    
// add this to make your struct conform to Hashable
extension ListAction: Hashable {
        static func == (lhs: Self, rhs: Self) -> Bool {
            lhs.uid == rhs.uid
        }
        func hash(into hasher: inout Hasher) {
            hasher.combine(uid)
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM