2016-05-15 83 views
0

我試圖使用自定義類作爲NSDictionary中的鍵。要做到這一點,按照編譯器,我需要實現NSCopying協議。我跟着this的建議,但它似乎不工作。這裏是我的代碼:Swift中的自定義鍵失敗

我的協議是什麼我的鑰匙類遵循:

// My custom protocol 
protocol TestProtocol: NSCopying { 
    func testFunc() 
} 

當我實現NSCopying協議類返回自己一切似乎只是很好地工作:

// Custom key class 
class KeyClass: NSObject, TestProtocol { 
    func testFunc() { 
    } 

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

現在當我調用代碼時:

let key = KeyClass() 
    let dictionary = NSMutableDictionary() 

    dictionary.setObject("TestString", forKey: key) 

    let value = dictionary[key] 

值包含「TestString」

但是當我到這個改變KeyClass實現從另一個棧話題像:

class KeyClass: NSObject, TestProtocol { 
    func testFunc() { 
    } 

    required override init() { 
    } 

    required init(_ model: KeyClass) { 
    } 

    func copyWithZone(zone: NSZone) -> AnyObject { 
     return self.dynamicType.init(self) 
    } 
} 

我一直在價值變量中獲得零。任何人都可以向我解釋爲什麼上面的實現不起作用?

回答

0

我猜測協議繼承者不適用於OC對象。因此請嘗試像[KeyClass:String]這樣的快速字典,或者不要繼承任何協議。

+0

Nah,沒有這樣的要求 – Sayaki

+0

@Sayaki這是因爲'NSObjectProtocol'包含'Hashable'。用新內容更新了我的答案。 – Lumialxk