2016-12-28 86 views
1

我有枚舉這樣的:Swift:如何使用枚舉作爲密鑰對哈希映射進行編碼?

enum Direction : String { 
     case EAST = "east" 
     case SOUTH = "south" 
     case WEST = "west" 
     case NORTH = "north" 
    } 

和我有一個變量被稱爲結果是使用這些枚舉方向爲關鍵一個HashMap中。

var result = [Direction:[String]]() 

我試着對這個對象進行編碼並通過multipeer框架發送給對方。但是,它在編碼器上失敗。

aCoder.encode(self.result, forKey: "result") 

錯誤說: 「編碼(與aCoder:NSCoder) ***終止應用程序由於未捕獲的異常 'NSInvalidArgumentException',原因是:「 - [_ SwiftValue encodeWithCoder:]:無法識別的選擇發送到實例0x17045f230 「

我怎麼能編碼此HashMap?

感謝。

+2

請注意,這是使用'lowerCamelCase',枚舉案件斯威夫特約定(這不是Java!)。我還假設你在說Hashmap時指的是'Dictionary'。另外'var result = [Direction [String]]'是無效的Swift,你的意思是'var result = [Direction:[String]]()'或'var result:[Direction:[String]]'? – Hamish

+0

這是一篇重複的文章。 http://stackoverflow.com/questions/24562357/how-can-i-use-a-swift-enum-as-a-dictionary-key-conforming-to-equatable – mrabins

+0

是的,我的意思是var result = [Direction: [String]]() – user6539552

回答

3

作爲日航的評論NSCoding功能說明是基於Objective-C運行,所以你需要將您的字典轉換爲可安全轉換爲NSDictionary的內容。

例如:

func encode(with aCoder: NSCoder) { 
    var nsResult: [String: [String]] = [:] 
    for (key, value) in result { 
     nsResult[key.rawValue] = value 
    } 
    aCoder.encode(nsResult, forKey: "result") 
    //... 
} 
required init?(coder aDecoder: NSCoder) { 
    let nsResult = aDecoder.decodeObject(forKey: "result") as! [String: [String]] 
    self.result = [:] 
    for (nsKey, value) in nsResult { 
     self.result[Direction(rawValue: nsKey)!] = value 
    } 
    //... 
} 
+0

如果我的設置是這樣的結構: [AnotherEnumType:[方向:[字符串]]] 爲什麼我沒有寫 VAR nsResult:[字符串:字符串:[平鋪]]] = [:[: [Tile]]] – user6539552

+0

@ user6539552,請編輯您的問題並顯示更具體的例子,指定如何定義AnotherEnumType和Tile。 – OOPer

+0

謝謝,它解決了我的問題! – user6539552