gpt4 book ai didi

swift - 有没有办法知道 Swift 是如何计算 hashValue 的?

转载 作者:可可西里 更新时间:2023-11-01 01:56:50 26 4
gpt4 key购买 nike

我最近发现下面的代码以散列冲突告终。

仅供引用,我使用的是 XCode 9.4.1 (9F2000),它使用 Swift 4.1.2

import Foundation

let lhs = "あいうえおあいう21あいうえ"
let rhs = "あいうえおあいう22あいうえ"
let percentEncodedLhs = lhs.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!
let percentEncodedRhs = rhs.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!

let lhsHashValue = lhs.hashValue
let rhsHashValue = rhs.hashValue
let lhsPercentHashValue = percentEncodedLhs.hashValue
let rhsPercentHashValue = percentEncodedRhs.hashValue

print(lhsHashValue == rhsHashValue)
print(lhsPercentHashValue == rhsPercentHashValue)

/*
Output:

false
true
*/

我知道在某些情况下会发生哈希冲突,但我找不到Swift 如何计算字符串的哈希值

例如,Java 计算 String 的 hashCode 是这样的: https://docs.oracle.com/javase/6/docs/api/java/lang/String.html#hashCode()

是否有任何官方解释或一些假设?

最佳答案

but I couldn't find how Swift calculates hashValue for String

你为什么不能? Swift 是开源的。如果您有兴趣,请阅读源代码。

https://github.com/apple/swift/blob/111499d2bfc58dc12fcb9cd1ce1dda7978c995b7/stdlib/public/core/StringHashable.swift

关于swift - 有没有办法知道 Swift 是如何计算 hashValue 的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52231963/

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