1

Looking through the hashable protocol, and to make a matrix location struct to conform:

struct MatrixLocation: Hashable {
    let row: Int
    let col: Int
    var hashValue: Int { return row.hashValue ^ col.hashValue }
}  

The hash value has the ^ operator.

What is the ^ operator in Swift?

Papershine
  • 4,995
  • 2
  • 24
  • 48
stevenpcurtis
  • 1,907
  • 3
  • 21
  • 47

1 Answers1

2

^ is the XOR operator in Swift. Basically it compares the bits of the two operands, and for each bit, it sets the corresponding bit of the result to 1 if one of the two input bits is 1, but the other is 0. If both bits are 1 or both bits are 0, it sets the bit in the result to 0.

So if you have 0x49 ^ 0x13, that would be 01001001 XOR 00010011, which would come out to 01011010, or 0x5a.

Charles Srstka
  • 16,665
  • 3
  • 34
  • 60
  • Because it's a quick and easy way to combine the two existing hash values in a way that comes out relatively unique. If you just ORed them you'd end up with a disproportionate number of 1 bits, and if you ANDed them, you'd end up with a disproportionate number of 0 bits. Each bit has a 50/50 chance of being 0 or 1 in an XOR operation, unlike those two. – Charles Srstka Mar 17 '18 at 03:02
  • 3
    XOR is quick and easy, but not actually a good choice for combining hash values. Check out [this answer](https://stackoverflow.com/a/27952689/77567) for an example of a much better hash combiner. – rob mayoff Mar 17 '18 at 03:51