字典键需要符合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
?
最佳答案
平等可以作为对象标识来实现,即 a == b
iff a
和 b
引用该类的同一实例,哈希值可以从 ObjectIdentifier
构建(对于相同的对象来说是相同的,例如 Difference between using ObjectIdentifier() and '===' Operator 进行比较):
对于 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
协议(protocol)。
关于swift - 引用作为 swift 字典中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37873604/