arrays - 修改字典数组内部的字典属性。错误: Cannot assign to immutable expression of type [String:AnyObject]

标签 arrays swift dictionary

SO like this 上有多个帖子,建议的唯一可行的解​​决方案是在同一索引处手动删除和插入属性。

但这感觉很困惑,并且一些帖子表明,如果在字典数组内,则可以在 Xcode 7 中直接更新字典属性。

但是,它不适用于下面的代码,生成 Cannot allocate to immutable expression of type [String:AnyObject] 错误。

// Class vars
var userDict = [String:AnyObject]()
var accounts = [[String:AnyObject]]()

func setHistory(index: Int, history: [String]) {
    (userDict["accounts"] as! [[String:AnyObject]])[index]["history"]! = history
    (userDict["accounts"] as! [[String:AnyObject]])[index]["history"] = history
    userDict["accounts"][index]["history"] = history
    userDict["accounts"][index]["history"]! = history
}

setHistory 内的所有四行都尝试做同样的事情,但都失败了。

最佳答案

现在你这样做的方式: userDict["accounts"] 为! [[String:AnyObject]])[索引]["历史记录"] 您正在使用不可变的容器。

你必须这样设计:

func setHistory(index: Int, history: [String]) {
    //this line copies from user dict,  it is not a pointer
    var account = userDict["accounts"] as! [[String:AnyObject]];
    //this line sets the new history
    account[index]["history"] = history;
    //this line will update the dictionary with the new data
    userDict["accounts"] = account


}

关于arrays - 修改字典数组内部的字典属性。错误: Cannot assign to immutable expression of type [String:AnyObject],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34376729/

相关文章:

objective-c - 如何在 Objective c 的类中创建静态 NSMutableArray?

ios - 将属性转换为 URL/NSURL

c - 使用 fgets() 将字符放入数组会创建自动输入吗?

php - 在数组中使用随机变量

Javascript 数组初始化行为

python - 在字典中添加键/值时出现非期望的 "int to tuple"转换

python - 按最接近的值对字典进行排序

ios - 使用 RxSwift 循环

xcode - 如何首先将新数据加载到 TableView - Swift

dictionary - Swift - map 注释的更好方法