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

Set all dictionary keys to 1 causes crash BAD_ACCESS Swift

我有一个字典,保存为 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
}

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

edit/update:在 Swift 4 或更高版本中,您可以使用 Dictionary mapValues 方法将所有字典值更改为 1,如下所示:

UserDefaults.standard.set(["apple": 0, "banana" : 1], forKey: "fruits")

var fruitDictionary = UserDefaults.standard.dictionary(forKey: "fruits") as? [String:Int] ?? [:]

func setFruit() {
    //Set all dictionary items to have the value 1
    fruitDictionary = fruitDictionary.mapValues({ _ in 1 })
    UserDefaults.standard.set(fruitDictionary, forKey: "fruits") //Save fruit dictionary
}

setFruit()

fruitDictionary["apple"] // 1