gpt4 book ai didi

swift - Swift 的 hash 和 hashValue 的区别

转载 作者:IT王子 更新时间:2023-10-29 05:08:26 25 4
gpt4 key购买 nike

Swift 中的Hashable 协议(protocol)要求您实现一个名为hashValue 的属性:

protocol Hashable : Equatable {
/// Returns the hash value. The hash value is not guaranteed to be stable
/// across different invocations of the same program. Do not persist the hash
/// value across program runs.
///
/// The value of `hashValue` property must be consistent with the equality
/// comparison: if two values compare equal, they must have equal hash
/// values.
var hashValue: Int { get }
}

不过,似乎还有一个类似的属性,叫做hash

hashhashValue 有什么区别?

最佳答案

hashNSObject protocol 中的必需属性,它对所有 Objective-C 对象的基础方法进行了分组,因此早于 Swift。默认实现只返回对象地址,正如你所看到的 NSObject.mm , 但可以覆盖该属性在 NSObject 子类中。

hashValue 是 Swift Hashable 协议(protocol)的必需属性。

两者都通过 NSObject 扩展连接Swift 中的标准库 ObjectiveC.swift :

extension NSObject : Equatable, Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
open var hashValue: Int {
return hash
}
}

public func == (lhs: NSObject, rhs: NSObject) -> Bool {
return lhs.isEqual(rhs)
}

(关于open var的含义,参见What is the 'open' keyword in Swift?。)

因此 NSObject(以及所有子类)符合 Hashable协议(protocol),以及默认的 hashValue 实现返回对象的 hash 属性。

isEqual 方法之间存在类似的关系NSObject 协议(protocol),以及 Equatable 中的 == 运算符协议(protocol):NSObject(和所有子类)符合Equatable协议(protocol),以及默认的 == 实现在操作数上调用 isEqual: 方法。

关于swift - Swift 的 hash 和 hashValue 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38946690/

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