Swift 4 : Inbuilt String. hashValue 为不同的字符串生成相同的结果

标签 swift

在使用Swift内置的字符串hashValue生成哈希值时,我们发现了两个不同的字符串生成相同哈希值的情况……但是碰撞的原因非常扑朔迷离……

取这两个字符串:

var str1 = """
00000000000000
00000000000000
00000000000000
00000000000000
00000000000000
00000000100000
00000000000000
00000000000
""" //Contains a single 1 character
var str2 = """
00000000000000
00000000000000
00000000000000
00000000000000
00000000000000
00000000000000
00000000000000
00000000000
""" //Contains only zeroes

str1 == str2 // false
str1.hashValue == str2.hashValue // true ..WAT?
  • 如果我们用一个字符修剪两个字符串,则哈希值不同
  • 如果我们追加不同字符,哈希值就会不同
  • 如果我们附加相同字符,则哈希值是相同

很想了解这里发生了什么......

谢谢

最佳答案

查看来自 Apple 的官方文档 Hashable协议(protocol)。它说:

A hash value, provided by a type’s hashValue property, is an integer that is the same for any two instances that compare equally. That is, for two instances a and b of the same type, if a == b, then a.hashValue == b.hashValue. The reverse is not true: Two instances with equal hash values are not necessarily equal to each other.

阅读这篇post您还可以获得更多

关于Swift 4 : Inbuilt String. hashValue 为不同的字符串生成相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49725087/

相关文章:

swift - 如何使用 POST 上传文件附件?

ios - Firebase 应用程序邀请在 swift ios 上崩溃

ios - 是否可以在 Swift 中创建通用闭包?

ios - CAGradientLayer 导致 subview 不可见

design-patterns - 快速程序接口(interface)

Swift MacOX - Popover segue 创建多个 View Controller 实例,但在它们被关闭时不会销毁它们

ios - swift : Making a get request to Get source code

ios - Swift - UICollectionView 在一行中显示多个项目

ios - Azure 媒体服务 Fairplay DRM AVPlayer 快速实现

ios - iOS 10 中添加到 UIApplication.shared.keyWindow 的 UIView 不可见