Search code examples
arraysswifthashable

will hasher.combine(self) cause trouble while using collections?


Can using this implementation of hash(into:) cause problems, especially using collections and arrays?:

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

Solution

  • I'm farily certain that hasher.combine(self) would either not compile or result in an infinite loop.

    When hasher.combine() sees the type that it is given, it is going to look for that objects hash(into:) function, which will call hasher.combine() with the same type, and so on and so forth.

    What you should do is

    func hash(into hasher: inout Hasher) {
        hasher.combine(property1)
        hasher.combine(prop2)
        //...
        //...
        //...
        //...
        //...
        //...
        //until you have written a line to combine every property you want to hash
    }
    

    Let me know if you have any questions.