字典键要求Hashable符合性:
Hashable
class Test {} var dictionary = [Test: String]() // Type 'Test' dies not conform to protocol 'Hashable' class Test: NSObject {} var dictionary = [Test: String]() // Works
如何获得纯Swift类实例的地址用作hashValue?
hashValue
可以将相等实现为对象标识,即a == biff a并b引用该类的相同实例,并且可以从构造哈希值ObjectIdentifier(对于相同的对象,该值相同,请比较,例如,使用ObjectIdentifier()和’===’运算子
a == b
a
b
ObjectIdentifier
对于Swift 4.2及更高版本:
class Test : Hashable { static func ==(lhs: Test, rhs: Test) -> Bool { return lhs === rhs } public func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } }
对于Swift 3:
class Test : Hashable { var hashValue: Int { return ObjectIdentifier(self).hashValue } } func ==(lhs: Test, rhs: Test) -> Bool { return lhs === rhs }
对于Swift 2.3及更早版本,您可以使用
/// Return an UnsafePointer to the storage used for `object`. There's /// not much you can do with this other than use it to identify the /// object func unsafeAddressOf(object: AnyObject) -> UnsafePointer<Void>
即
class Test : Hashable { var hashValue: Int { return unsafeAddressOf(self).hashValue } } func ==(lhs: Test, rhs: Test) -> Bool { return lhs === rhs }
例:
var dictionary = [Test: String]() let a = Test() let b = Test() dictionary[a] = "A" print(dictionary[a]) // Optional("A") print(dictionary[b]) // nil
实施Equatable协议。
Equatable