Swift的hash和hashValue之间的区别

cfi*_*her 26 hash swift swift-protocols

HashableSwift中的协议要求您实现一个名为的属性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 }
}
Run Code Online (Sandbox Code Playgroud)

然而,似乎还有类似的属性叫做hash.

hash和之间有什么区别hashValue

Mar*_*n R 36

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

hashValue是Swift Hashable协议的必需属性.

两者都通过ObjectiveC.swift中NSObject 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)
}
Run Code Online (Sandbox Code Playgroud)

(有关含义open var,请参阅Swift中的'open'关键字是什么?)

所以NSObject(和所有子类)符合Hashable 协议,默认hashValue实现返回hash对象的属性.

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

  • @DeclanMcKenna:“hashValue”和“hash”应该为“NSObject”子类返回相同的值(内存地址),除非在子类中被覆盖。该内存地址*可以*在程序的多次运行中是相同的,但您不能依赖它。 (2认同)