将所有字典键设置为1会导致崩溃BAD_ACCESS Swift

时间:2015-02-28 13:46:25

标签: swift dictionary

我有一个字典,保存为全局声明的NSUserDefault

var fruitDictionary = NSUserDefaults().objectForKey("fruits") as [String:Int]

此字典包含水果名称,然后是0或1的值。我尝试使用以下方法将所有值设置为1(其中大多数当前设置为0):

func setFruit() {

    //Set all dictionary items to have the value 1
    for key in fruitDictionary.keys{
        fruitDictionary[key] = 1 //Crashes here: EXC_BAD_ACCESS Code=1
    }

    defaults.setObject(fruitDictionary, forKey: "fruits") //Save fruit dictionary
}

关于这可能是什么原因或我应该如何调试它的任何想法?

1 个答案:

答案 0 :(得分:0)

var fruitsDictionary : [String:AnyObject] = [:]

fruitsDictionary["apple"] = 5
fruitsDictionary["orange"] = 3
fruitsDictionary["banana"] = 12

NSUserDefaults.standardUserDefaults().setObject(fruitsDictionary, forKey: "fruits")

if let fruits = NSUserDefaults.standardUserDefaults().dictionaryForKey("fruits") as? [String:Int] {
    for (fruit,amount) in fruits {
        println("\(fruit) = \(amount)")
    }
}