6

I have a struct in Swift that looks like this:

internal struct MapKey {
    internal let id: String
    internal let values: [String:String]
}
extension MapKey: Equatable {}
func ==(lhs: MapKey, rhs: MapKey) -> Bool {
    return lhs.id == rhs.id && lhs.values == rhs.values
}

I now have the need to use MapKey as the key in a Swift dictionary, which requires MapKey to conform to the Hashable protocol.

What would a correct implementation of Hashable be for a struct like this one?

extension MapKey: Hashable {
    var hashValue: Int {
        return ??? // values does not have a hash function/property.
    }
}

I've been doing some research but failed to identify what the proper way to hash a dictionary is, as I need to be able to generate a hash value for values property itself. Any help is much appreciated.

unbekant
  • 1,555
  • 22
  • 31

3 Answers3

4

I think you need to review your data model if you have to use a whole struct as a dictionary key. Anyhow, here's one way to do it:

internal struct MapKey: Hashable {
    internal let id: String
    internal let values: [String:String]

    var hashValue: Int {
        get {
            var hashString = self.id + ";"
            for key in values.keys.sort() {
                hashString += key + ";" + values[key]!
            }

            return hashString.hashValue
        }
    }
}

func ==(lhs: MapKey, rhs: MapKey) -> Bool {
    return lhs.id == rhs.id && lhs.values == rhs.values
}

This assumes that you don't have semicolon (;) in id or in the keys and values of values. Hasable implies Equatable so you don't need to declare it conforming to Equatable again.

Code Different
  • 90,614
  • 16
  • 144
  • 163
  • 2
    You need not make any assumptions about the semicolon (and inserting such a separator isn't necessary) because hashes need not be unique. – Martin R Jun 23 '16 at 20:47
  • Agreed with @MartinR. Thanks for the idea Code, this will solve my current needs, appreciate the advice to review the data model as well, will keep that in mind. – unbekant Jun 23 '16 at 21:23
  • Correct me if I'm wrong. Reading this [answer](http://stackoverflow.com/a/31666711/5175709) I think you **do** need to implement Equatable separately *again* – mfaani Nov 18 '16 at 16:32
  • @Honey you don't have to declare conformance to Equatable because Hashable already imply that. The == functions provides the implementation required by Equatable. – Code Different Nov 18 '16 at 17:13
  • @CodeDifferent isn't that exactly what the linked answer is telling you **should** do? I mean if by any chance your hashvalue are same, then it would switch to equatable function and try that. Or is that about a different matter? Can you please explain? – mfaani Nov 18 '16 at 17:48
  • *Your code uses the same implementation for hash and equality, and this will guarantee a collision* – mfaani Nov 18 '16 at 17:55
  • I finally cracked it, and wrote my answer [here](http://stackoverflow.com/a/40685353/5175709) Hopefully it would be beneficial to others who had the same confusion. – mfaani Nov 18 '16 at 20:22
1

Since both id and values are immutable both are ok to use as basis for equals and hashValue. However - if MapKey.id (which the name somewhat implies) uniquely identifies the MapKey (at least within the context of one dictionary) then it is both easier and more performant to just use the MakKey.id as basis for == operator as well as hashValue

    internal struct MapKey: Hashable {
        internal let id: String
        internal let values: [String:String]

        var hashValue: Int {
            get { return  self.id.hashValue}
        }
    }

    func ==(lhs: MapKey, rhs: MapKey) -> Bool {
        return lhs.id == rhs.id
    }
Eric Linde
  • 191
  • 6
  • Good observation Eric. Unfortunately it is the combination of id + values that makes a Key unique in my case, even though the id would make you think otherwise. I might have not chosen the best names for my example. – unbekant Jun 23 '16 at 21:25
0

foundation data types are Hashable in Swift 4.2, you only need to let your MapKey struct to conform Hashable protocol:

struct MapKey: Hashable {
    let id: String
    let values: [String: String]
}

in case you want to use a class, you need conform hash(:) func like this:

class MapKey: Hashable {
    static func == (lhs: MapKey, rhs: MapKey) -> Bool {
        return lhs.id == rhs.id && lhs.values == rhs.values
    }

    let id: String = ""
    let values: [String: String] = [:]

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
        hasher.combine(values)
    }
}
Cuong Nguyen
  • 376
  • 1
  • 5
  • 8