使用按位异或运算符将哈希值相加或简单地将它们相加

Adding hashValues together using Bitwise XOR Operator or simply adding them together

我想在我的 class 中使用以下方法创建一些属性的唯一标识符:

class Foo {
    var name = "John"
    var array = ["string1", "string2"]

    var check: Bool { return name.isEmpty }

    var xor: Int { return name.hashValue ^ check.hashValue }
    var add: Int { return name.hashValue + check.hashValue }
}

let test = Foo()

print(test.xor) // prints 4799450059756749538
print(test.add) // prints 4799450059756749538

工作没有问题。

但是在阅读一些教程时,一些网站使用运算符 ^ 来 "add" 哈希值。

我的问题是,如果我使用运算符 ^ 来计算 identifier 是否有任何(负面)影响?因为当我计算数组的哈希值时,我不能使用运算符 + 并且我不得不使用 ^ 代替(除非我使用 Int32/Int64 代替):

var identifier: Int { return name.hashValue ^ array.map { [=11=].hashValue }.reduce(0) { [=11=] ^  } ^ check.hashValue }

我还看到有人在处理哈希值时使用按位左右移位运算符。这有什么特别的原因吗?

+ 上使用 ^ (bitwise exclusive-OR) 的原因是 + 会溢出并使您的崩溃应用

之所以使用按位左右移位运算符,是因为数组顺序不同,会产生不同的哈希值。如果您只是 ^ 哈希值而不移动,那么 ["a", "b"]["b", "a"] 将生成相同的哈希值。