我有一个由一堆属性组成的 NSObject。NSObject 可以使用 Date 属性和 String 属性来唯一标识。使用这两个变量创建哈希的最佳方法是什么?
我可以做类似的事情 date.hashValue ^ string.hashValue,但似乎每个对象的哈希值都不同。
该对象看起来像这样:
class Something : Model {
public var name: String!
public var time: Date!
override var hash : Int {
return time.hashValue ^ name.hashValue
}
}
Run Code Online (Sandbox Code Playgroud)
对于NSObject子类,您必须重写hash属性和isEqual:方法,比较Swift 中的 NSObject 子类: hash 与 hashValue、isEqual 与 ==。
对于该属性的实现,hash您可以使用HasherSwift 4.2 中引入的类及其combine()方法:
将给定值添加到该哈希器,将其基本部分混合到哈希器状态中。
我还建议使属性保持不变,因为在将对象插入可散列集合(集合、字典)后对它们进行变异会导致未定义的行为,请比较Swift mutable set: Duplicate element found。
class Model: NSObject { /* ... */ }
class Something : Model {
let name: String
let time: Date
init(name: String, time: Date) {
self.name = name
self.time = time
}
override var hash : Int {
var hasher = Hasher()
hasher.combine(name)
hasher.combine(time)
return hasher.finalize()
}
static func ==(lhs: Something, rhs: Something) -> Bool {
return lhs.name == rhs.name && lhs.time == rhs.time
}
}
Run Code Online (Sandbox Code Playgroud)