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/