簡體   English   中英

如何將 NSDictionary 存儲在 String:String 中?

[英]How can I store an NSDictionary in a String:String?

我正在嘗試將 plist(鍵是唯一的單詞,值是它們的英語定義)加載到字典中。 我可以像這樣一次性完成:

let definitionsFile = URL(fileURLWithPath: Bundle.main.path(forResource: "word_definitions", ofType:"plist")!)
let contents = NSDictionary(contentsOf: definitionsFile)
guard let value = contents!.object(forKey: lastGuess) as? String else {
      print("value from key fail")
      return
} 

...但是每次我使用它時它都必須加載文件。 所以我嘗試將代碼移動到程序加載器並將數據存儲在定義字典中(大寫的消息是問題區域):

let definitionsFile = URL(fileURLWithPath: Bundle.main.path(forResource: "word_definitions", ofType:"plist")!)
if let contents = NSDictionary(contentsOf: definitionsFile) as? [String : String] {
    print("loaded definitions dictionary")
    if case state.definitions = contents {
        print("added definitions to state")
    } else {
        print("FAILED TO ADD DEFINITIONS TO STATE")
    }
} else {
    print("failed to load definitions dictionary")
}

它在我將它分配給 state.definitions (這是一個 String:String 字典)的地方失敗了。 有什么我想念的嗎? 我是否需要將 state.definitions 更改為 String:Any 並重寫每次訪問?

更新:根據 Tom Harrington 的評論,我嘗試將 state.definitions 顯式創建為 NSDictionary (刪除 as [String:String] 位),但它仍然沒有存儲字典。

我將您的代碼放在一個 Playground 中,該 Playground 都生成一個 plist 文件,然后使用 NSDictionary 將其解析出來。 這里是完整的游樂場

import Foundation

let stringPairs = [
    "One" : "For the Money",
    "Two" : "For the Show",
    "Three" : "To Get Ready",
    "Four" : "To Go",
]

let tempDirURL = FileManager.default.url(for: .itemReplacementDirectory,
                                      in: .userDomainMask,
                                      appropriateFor: Bundle.main.bundleURL,
                                      create: true)
let demoFileURL = tempDirURL.appendingPathComponent("demo_plist.plist")
do {
    if let plistData = try? PropertyListSerialization.data(
        fromPropertyList: stringPairs,
        format: .xml,
        options: 0) {
        try plistData.write(to: demoFileURL)
    }
} catch {
    print("Serializing the data failed")
}

struct State {
    var definitions: [String: String]
}

var state = State(definitions: [:])

if let fileContent = NSDictionary(contentsOf: demoFileURL),
   let contents = fileContent as? [String : String] {
    print("loaded definitions dictionary")
    state.definitions = contents
} else {
    print("failed to load definitions dictionary")
}

debugPrint(state.definitions)

請注意,我只是為state變量及其類型編造了一些東西。

它似乎工作得很好並打印:

loaded definitions dictionary
["Four": "To Go", "Two": "For the Show", "One": "For the Money", "Three": "To Get Ready"]

我改變的一件事是你的if case ...聲明。 我完全確定這個結構在這種情況下意味着什么。 Swift 語言指南說if case后面應該跟着一個模式和一個初始化器。 在我的代碼中,“state.definitions”不是一種模式,所以if case總是返回 false。 但在我看來,這應該是某種編譯器錯誤。

無論如何,通過將contents的綁定拉入它自己的外部子句中, if我可以確定當我進入 if 內容不為空時。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM