修改字典的数组里面字典财产。错误:无法分配给类型的不可变的前pression [字符串:AnyObject] [英] Modifying dictionary property inside of array of dictionaries. Error: Cannot assign to immutable expression of type [String:AnyObject]
问题描述
有对SO <一个几个职位href=\"http://stackoverflow.com/questions/24721555/how-does-one-create-a-mutable-copy-of-an-immutable-array-in-swift\">like这,而唯一的解决方案建议,似乎工作手动删除和相同的索引中插入一个属性。
There are several posts on SO like this, and the only solution suggested that would seem to work is manually removing and inserting a property at the same index.
不过,这感觉凌乱,有的帖子建议它在X code 7可以直接更新字典的属性,如果字典的数组里面。
But this feels messy, and some posts suggest it's possible in Xcode 7 to directly update dictionary properties if inside an array of dictionaries.
但是,它不工作为code以下时,产生的无法分配给一成不变EX型$ P $ pssion [字符串:AnyObject]。
误差
However, it's not working for the code below, generating the Cannot assign to immutable expression of type [String:AnyObject]
error.
// 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
内尝试做同样的事情,所有的失败。所有的四行
All four lines inside of setHistory
try to do the same thing, and all fail.
推荐答案
现在的方式,你这样做是:的UserDict [账户]作为! [字符串:AnyObject]])[指数] [历史]
您正在使用一个不可变对象的工作。
Right now the way you are doing this:
userDict["accounts"] as! [[String:AnyObject]])[index]["history"]
you are working with an immutable container.
您将不得不设计出这样的:
You are going to have to design it like this:
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
}
这篇关于修改字典的数组里面字典财产。错误:无法分配给类型的不可变的前pression [字符串:AnyObject]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!