objective c - How to implement hashCode() in Swift for use by NSDictionary? -


i'm trying use swift object key in nsmutabledictionary. i've implemented hashvalue , equality usual , works in native swift dict. nsmutabledictionary never calls hash function. missing?

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 not call hash function, returns nil here. 

answer:

i had implement explicitly hash() , isequal() so:

@objc public func hash() -> int {     return hashvalue }  @objc public func isequal( obj : anyobject ) -> bool {     return (obj as? holder)?.val == val } 

nsdictionary uses hash , isequal methods nsobjectprotocol:

@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" 

however, if possible recommend sticking swift dictionary [holder:string], tried previously.


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -