在Swift中编写一个好的Hashable实现 [英] Writing a good Hashable implementation in Swift

查看:146
本文介绍了在Swift中编写一个好的Hashable实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C(和其他语言)中, - (NSUInteger)hash 的相对较好的默认实现可能是:

   - (NSUInteger)hash {
return 31u * [self.property1 hash] + [self.property2 hash];

$ / code>

假设 property1 property2 散列返回优质值。



在它的 Hashable 协议中定义的Swift的等效 var hashValue:Int 方法中不起作用。



等价的Swift代码可能会溢出,这是Swift中的一个运行时错误。

  var hashValue:Int {
return 31 * property1.hashValue + property2.hashValue // overflow-tastic
}

所以我的问题是,在Swift中生成哈希值(实现Hashable)的最佳技术是什么?我应该只使用XOR吗?虽然我的理解是XOR不适合创建统一的散列分布。也许更奇特的东西?正如Fabian Kreiser所建议的,可以使用溢出操作符来制作hashValue方法,如下所示:

  var hashValue:Int {
return(31& * property1.hashValue)& + property2.hashValue

$ / code>

该值仍然溢出,但至少不会崩溃


In Objective-C (and other languages) a relatively good default implementation of - (NSUInteger)hash might be:

- (NSUInteger)hash {
   return 31u * [self.property1 hash] + [self.property2 hash];
}

Assuming both property1 and property2 return good values for hash.

This doesn't work in Swift's equivalent var hashValue: Int method defined on its Hashable protocol.

The equivalent Swift code is likely to overflow and this a runtime error in Swift.

var hashValue: Int {
    return 31 * property1.hashValue + property2.hashValue // overflow-tastic
}

So my question is, what is the best technique for generating hash values (implementing Hashable) in Swift? Should I just use XOR? Though my understanding is that XOR is not ideal for creating uniform hash distributions. Perhaps something more exotic?

解决方案

As suggested by Fabian Kreiser one can use the overflow operators to make the hashValue method as follows:

var hashValue: Int {
    return (31 &* property1.hashValue) &+ property2.hashValue 
}

The value still overflows, but at least it doesn't crash

这篇关于在Swift中编写一个好的Hashable实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆