Prefer using the `hash(into:)` function instead of overriding `hashValue`SW-R1001
Overriding the hashValue
property in Swift for custom types is now considered an anti-pattern. Instead, use the hash(into:)
function to generate hash values for your objects. Here are a few reasons why:
Clarity: The hash(into:)
function is more explicit than hashValue
. It makes it clear that the intent is to generate a hash value and not just return a random integer. This helps other developers understand the purpose of the function and avoid common pitfalls.
Consistency: The hash(into:)
function is part of the Hashable protocol, which also requires ==
operator to be implemented. By using the same protocol, you ensure that your code is consistent with other types in the standard library. This makes it easier to reason about equality and hashing.
Performance: The hash(into:)
function takes advantage of Swift's new hashing algorithm, which is faster and more secure than the old one. By using this function, you ensure that your code benefits from these improvements.
In summary, overriding hashValue
for custom types is now considered an anti-pattern. Instead, use the hash(into:)
function to generate hash values for your objects. This will make your code clearer, more consistent with the standard library, and more performant.
Bad Practice
struct Person {
var name: String
var age: Int
var hashValue: Int {
return name.hashValue ^ age.hashValue
}
}
Recommended
struct Person: Hashable {
var name: String
var age: Int
func hash(into hasher: inout Hasher) {
hasher.combine(name)
hasher.combine(age)
}
}