Swift的hash和hashValue之间的区别 [英] Difference between Swift's hash and hashValue
问题描述
Swift中的Hashable
协议要求您实现一个名为hashValue
的属性:
The Hashable
protocol in Swift requires you to implement a property called 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
的相似属性.
However, it seems there's also a similar property called hash
.
hash
和hashValue
有什么区别?
推荐答案
hash
是 NSObject.mm ,但是可以覆盖该属性
在NSObject
子类中.
hash
is a required property in the NSObject
protocol, which groups methods that are fundamental to all Objective-C objects, so that predates Swift.
The default implementation just returns the objects address,
as one can see in
NSObject.mm, but one can override the property
in NSObject
subclasses.
hashValue
是Swift Hashable
协议的必需属性.
hashValue
is a required property of the Swift Hashable
protocol.
两者均通过NSObject
扩展名进行连接,该扩展名在
中的Swift标准库
ObjectiveC.swift :
Both are connected via a NSObject
extension defined in the
Swift standard library in
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
的含义,请参见什么是开放'Swift中的关键字?.)
(For the meaning of open var
, see What is the 'open' keyword in Swift?.)
所以NSObject
(以及所有子类)符合Hashable
协议和默认的hashValue
实现
返回对象的hash
属性.
So NSObject
(and all subclasses) conform to the Hashable
protocol, and the default hashValue
implementation
return the hash
property of the object.
的isEqual
方法之间存在相似的关系.
NSObject
协议和Equatable
中的==
运算符
协议:NSObject
(以及所有子类)符合Equatable
协议和默认的==
实现
在操作数上调用isEqual:
方法.
A similar relationship exists between the isEqual
method of the
NSObject
protocol, and the ==
operator from the Equatable
protocol: NSObject
(and all subclasses) conform to the Equatable
protocol, and the default ==
implementation
calls the isEqual:
method on the operands.
这篇关于Swift的hash和hashValue之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!