如何在Swift中实现hashCode()以供NSDictionary使用?

时间:2015-07-05 19:09:26

标签: objective-c swift hashcode

我正在尝试将Swift对象用作NSMutableDictionary中的键。我像往常一样实现了hashValue和相等,它适用于原生的Swift dict。但NSMutableDictionary永远不会调用我的哈希函数。我错过了什么?

public final class Holder : Hashable, NSCopying
{
    var val : Int = 0
    public init( _ val : Int ) { self.val = val }

    public var hashValue: Int {
        return val
    }

    @objc public func copyWithZone(zone: NSZone) -> AnyObject {
        return self
    }
}

public func == (lhs: Holder, rhs: Holder) -> Bool {
    return lhs.val==rhs.val
}

//var dict = Dictionary<Holder,String>()
var dict = NSMutableDictionary()

dict[ Holder(42) ]="foo"
dict[ Holder(42) ] // NSMutableDictionary will not call my hash function, returns nil here.

解答:

我必须像这样显式地实现hash()和isEqual():

@objc public func hash() -> Int {
    return hashValue
}

@objc public func isEqual( obj : AnyObject ) -> Bool {
    return (obj as? Holder)?.val == val
}

1 个答案:

答案 0 :(得分:0)

NSDictionary使用来自NSObjectProtocol的hash and isEqual methods

@objc var hash: Int { return hashValue }
@objc func isEqual(o: AnyObject?) -> Bool { return o as? Holder == self }

// ...

dict[ Holder(42) ] = "foo"
dict[ Holder(42) ] // returns "foo"

但是,如果可能的话,我建议您坚持使用Swift词典[Holder:String],就像之前尝试过的那样。