在swift词典中作为关键引用

Kir*_*ins 13 dictionary hashtable key memory-address swift

字典键需要Hashable符合:

class Test {}
var dictionary = [Test: String]() // Type 'Test' dies not conform to protocol 'Hashable'

class Test: NSObject {}
var dictionary = [Test: String]() // Works
Run Code Online (Sandbox Code Playgroud)

如何获取纯Swift类实例的地址hashValue

Mar*_*n R 18

对于Swift 3(Xcode 8 beta 6或更高版本),请使用a == b.

class Test : Hashable {
    static func ==(lhs: Test, rhs: Test) -> Bool {
        return lhs === rhs
    }

    public func hash(into hasher: inout Hasher) {
        hasher.combine(ObjectIdentifier(self))
    }
}
Run Code Online (Sandbox Code Playgroud)

然后aiff bObjectIdentifier引用该类的相同实例(Equatable在这种情况下满足).

例:

class Test : Hashable {
    var hashValue: Int { return ObjectIdentifier(self).hashValue }
}

func ==(lhs: Test, rhs: Test) -> Bool {
    return lhs === rhs
}
Run Code Online (Sandbox Code Playgroud)

对于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>
Run Code Online (Sandbox Code Playgroud)

实现哈希值,以及身份运算符a == b来实现a协议.