Swift的hash和hashValue之间的区别 [英] Difference between Swift's hash and hashValue

查看:874
本文介绍了Swift的hash和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.

hashhashValue有什么区别?

推荐答案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆