Swift 的 hash 和 hashValue 的区别
Difference between Swift's hash and hashValue
Swift 中的 Hashable
协议要求您实现一个名为 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
。
hash
和hashValue
有什么区别?
hash
是 NSObject
protocol 中必需的 属性,它对所有 Objective-C 对象的基础方法进行分组,因此早于 Swift。
默认实现只是 returns 对象地址,
正如你所看到的
NSObject.mm,但可以覆盖 属性
在 NSObject
个子类中。
hashValue
是 Swift Hashable
协议所必需的 属性。
两者都通过 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)
}
([=17=的含义],参见。)
所以NSObject
(和所有子类)符合Hashable
协议,以及默认的 hashValue
实现
return对象的hash
属性
的 isEqual
方法之间存在类似的关系
NSObject
协议,以及来自 Equatable
的 ==
运算符
协议:NSObject
(和所有子类)符合 Equatable
协议,以及默认的 ==
实现
在操作数上调用 isEqual:
方法。
Swift 中的 Hashable
协议要求您实现一个名为 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
。
hash
和hashValue
有什么区别?
hash
是 NSObject
protocol 中必需的 属性,它对所有 Objective-C 对象的基础方法进行分组,因此早于 Swift。
默认实现只是 returns 对象地址,
正如你所看到的
NSObject.mm,但可以覆盖 属性
在 NSObject
个子类中。
hashValue
是 Swift Hashable
协议所必需的 属性。
两者都通过 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)
}
([=17=的含义],参见
所以NSObject
(和所有子类)符合Hashable
协议,以及默认的 hashValue
实现
return对象的hash
属性
的 isEqual
方法之间存在类似的关系
NSObject
协议,以及来自 Equatable
的 ==
运算符
协议:NSObject
(和所有子类)符合 Equatable
协议,以及默认的 ==
实现
在操作数上调用 isEqual:
方法。