Swift的hash和hashValue之间的区别

Swift的hash和hashValue之间的区别

本文介绍了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协议,该协议对所有Objective-C对象至关重要的方法进行了分组,因此早于Swift.默认实现只是返回对象地址,如人们所见 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 inNSObject.mm, but one can override the propertyin 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 theSwift standard library inObjectiveC.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 Hashableprotocol, and the default hashValue implementationreturn the hash property of the object.

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

A similar relationship exists between the isEqual method of theNSObject protocol, and the == operator from the Equatableprotocol: NSObject (and all subclasses) conform to the Equatableprotocol, and the default == implementationcalls the isEqual: method on the operands.

这篇关于Swift的hash和hashValue之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:43