Duncan Rowland Duncan Rowland - 5 months ago 31
Swift Question

Do swift hashable protocol hash functions need to return unique values?

I am working through an iOS swift Tetris tutorial* and have it completed and working.
But I am puzzled about one particular aspect - the Hashable protocol.
The function:

class Block: Hashable, Printable {
[...]
var hashValue: Int { return self.column ^ self.row }


Rows go 0..9, and Columns 0..20. The notes says of this function "We return the exclusive-or of our row and column properties to generate a unique integer for each Block.". But my understanding is that 0^1 would be the same as 1^0, etc... I would like to know if it is a problem if the Hash function is not unique like this, or are collisions are generally OK? As I say, the application appears to work fine...

*https://www.bloc.io/tutorials/swiftris-build-your-first-ios-game-with-swift#!/chapters/681

Answer

Collisions are not "generally OK". The underlying assumption is that the hash value of x is the hash value of y if and only if x == y. If you consider column 2, row 1 the same as column 1, row 2, then fine. But I don't think you do! The application may appear to work, but presumably you have done nothing that requires hashability - yet.

Comments