Swift hash & hashValue区别

最后更新: 2017-07-22

Swift标准库中,NSObjectProtocol协议

public var hash: Int { get }

Equatable协议:

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 { get }
}

区别:

hash在OC 中或者Swift中都是对象的基础功能之一,返回的是对象的地址,可以通过NSObject.mm查看到。

hashValue 是在 Hashable 协议中定义的。

但是,在默认实现上面 hashValue 返回的就是hash 的值 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.
  @objc
  open var hashValue: Int {
    return hash
  }
}

// 注意此处
public func == (lhs: NSObject, rhs: NSObject) -> Bool {
  return lhs.isEqual(rhs)
}
原文地址:https://www.cnblogs.com/gaox97329498/p/12070170.html