参考作为swift字典的关键 [英] Reference as key in swift dictionary
本文介绍了参考作为swift字典的关键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
字典键需要 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
?
How to get address of pure Swift class instance to use as hashValue
?
推荐答案
对于Swift 3(Xcode 8 beta 6或更高版本),使用 ObjectIdentifier
。
For Swift 3 (Xcode 8 beta 6 or later), use ObjectIdentifier
.
class Test : Hashable {
// Swift 2:
var hashValue: Int { return unsafeAddressOf(self).hashValue }
// Swift 3:
var hashValue: Int { return ObjectIdentifier(self).hashValue }
}
func ==(lhs: Test, rhs: Test) -> Bool {
return lhs === rhs
}
然后 a == b
iff a
和 b
指的是同一个实例在这种情况下,课程(
和 a.hashValue == b.hashValue
)。
Then a == b
iff a
and b
refer to the same instance of the class (
and a.hashValue == b.hashValue
is satisfied in that case).
示例:
var dictionary = [Test: String]()
let a = Test()
let b = Test()
dictionary[a] = "A"
print(dictionary[a]) // Optional("A")
print(dictionary[b]) // nil
对于Swift 2.3及更早版本,您可以使用
For Swift 2.3 and earlier, you could use
/// 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>
实现哈希值,身份运算符 ===
实现 Equable
协议。
to implement a hash value, and the identity operator ===
to
implement the Equatable
protocol.
这篇关于参考作为swift字典的关键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文