gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:59:49 24 4
gpt4 key购买 nike

在使用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com