小编典典

快速字典中作为键的引用

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


阅读 276

收藏
2020-07-07

共1个答案

小编典典

可以将相等实现为对象标识,即a == biff
ab引用该类的相同实例,并且可以从构造哈希值ObjectIdentifier(对于相同的对象,该值相同,请比较,例如,使用ObjectIdentifier()和’===’运算子

对于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协议。

2020-07-07