swift - 引用作为 swift 字典中的键

标签 swift dictionary key hashtable memory-address

字典键需要符合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 ab 引用该类的同一实例,哈希值可以从 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/

相关文章:

Swift 无法识别来自 Obj-C 类的方法

Swift.print() 与 print()

ios - 可重用 UITableHeaderFooterView 松散 ImageView 方向状态

python - 将文本从字典优先级替换为更长的字符串

c# - 比较列表 C# 中的字符

LINQ 查询输出键计数值对

swift - 在 swift 中用字符串中的其他字符替换多个字符的更简单方法是什么?

javascript - 使用数字键访问非数字键对象是否有效?

windows - 批处理文件调用 VBS,它向应用程序发送 key

PHP array_keys - 我做错了什么?