我一直在坐在一个问题太久,我真的不明白为什么会发生这种情况。我在网上搜索了解决方案,我尝试了其中的每一个,但仍然遇到了这个问题。我在Swift中初始化一个字典,然后向它添加一些值,但是在我添加键/值后,字典是空的(在调试模式下检查),在尝试读取它时也没有在代码中出现。这是我当前的代码:Swift Dictionary filled但仍为空
我第一次得到我想要的加我的字典中的plist:
var path = NSBundle.mainBundle().pathForResource("Questions", ofType: "plist")
var dict = NSDictionary(contentsOfFile: path!)!
var questionsArr = dict.objectForKey("Math") as NSArray
var questionsMutableArray:NSMutableArray = questionsArr.mutableCopy() as NSMutableArray
然后,我创建并添加值,我的字典
//I have also tried with this and got the same result: var newDict = Dictionary<String, String>()
var newDict = [String: String]()
newDict["Question"] = "What is 1+1"
newDict["A"] = "One"
newDict["B"] = "Two"
newDict["C"] = "Three"
的newDict似乎空在这里调试模式。 然后我写的词典我的plist:
questionsMutableArray.addObject(newDict)
questionsMutableArray.writeToFile(path!, atomically: true)
后来在代码中,我得到我的plist这样的(这时候我没有加入newDict前工作:
var path = NSBundle.mainBundle().pathForResource("Questions", ofType: "plist")
var dict = NSDictionary(contentsOfFile: path!)!
在最后线(NSDictinoary(contentsOfFile:!路径)我得到这个错误:?!
fatal error: unexpectedly found nil while unwrapping an Optional value
有谁知道为什么发生这种情况 帮助,将不胜感激
EDIT溶液4)
1. I'm getting an array of dictionaries from my plist (Questions).
2. I add a new dictionary to my array of dictionaries.
3. I write/save it to the plist.
4. I get the array from the plist again and investigate the content of it.
5. The new dictionary I just added is not there.
这是代码:
1) questionsArr是空
var bundlepath:NSString = NSBundle.mainBundle().pathForResource("Questions", ofType: "plist")!
var dict = NSMutableDictionary(contentsOfFile: bundlepath)!
var questionsArr = dict.objectForKey("Math") as NSArray
var questionsMutableArray:NSMutableArray = questionsArr.mutableCopy() as NSMutableArray
2) questionsMutableArray瓦特为空,现在有新的问题。
var newDict = [String: String]()
newDict["QuestionTitle"] = "What is 1+1?"
newDict["A"] = "One"
newDict["B"] = "Two"
newDict["C"] = "Three"
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
var path:NSString = documentsPath.stringByAppendingPathComponent("Questions.plist");
questionsMutableArray.addObject(newDict)
dict["Math"] = questionsMutableArray
3)
let didItSave = dict.writeToFile(path, atomically: true)
4) questionsArr仍然是空的。如果我使用'路径'而不是'bundlepath',它会起作用!
dict = NSMutableDictionary(contentsOfFile: bundlepath)! //<- I USED 'path' INSTEAD OF 'bundlepath' and now it works!
questionsArr = dict.objectForKey("Math") as NSArray
你可以显示代码,你发现它是零。发布的代码无助于确定问题 – 2015-02-09 22:32:22
不确定它是如何在swift中工作的,但是如果你想添加东西,你的字典需要是“可变的”。 – user3386109 2015-02-09 22:36:02
Swift中集合的可变性取决于您是否将字典赋予变量或常量,而不是像Objective-C中的类名称。 – 2015-02-09 22:39:26