在 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
协议的一个属性,详情请参考NSObject
protocol。在 Swift 中的NSObject
子类里,需要注意使用hash
而不是hashValue
,以及isEqual
而不是==
,具体可参考NSObject subclass in Swift: hash vs hashValue, isEqual vs ==。 - Martin R