且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

参考作为swift字典的关键

更新时间:2022-11-21 07:50:40

对于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.