繁体   English   中英

在字典数组内部修改字典属性。 错误:无法分配给类型为[String:AnyObject]的不可变表达式

[英]Modifying dictionary property inside of array of dictionaries. Error: Cannot assign to immutable expression of type [String:AnyObject]

有对SO几个职位是这样 ,唯一的解决办法建议,似乎工作手动删除和相同的指数插入一个属性。

但这感觉很混乱,并且一些帖子建议,如果在字典数组中,则可以在Xcode 7中直接更新字典属性。

但是,它不适用于下面的代码,生成Cannot assign 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所有四行setHistory试图做相同的事情,但都失败了。

现在,您的操作方式为: userDict["accounts"] as! [[String:AnyObject]])[index]["history"] userDict["accounts"] as! [[String:AnyObject]])[index]["history"]您正在使用不可变容器。

您将必须像这样设计它:

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


}

我认为您最好选择一个类来对数据进行建模。

无论如何,您可以从ObjC, NSMutableDictionary致电一位老朋友:

var userDict = [String: AnyObject]()
var accounts = [NSMutableDictionary]()

accounts.append(["history": ["history1.1", "history1.2"]])
accounts.append(["history": ["history2.1", "history2.2"]])
userDict["accounts"] = accounts

func setHistory(index: Int, history: [String]) {
    userDict["accounts"]![index].setObject(history, forKey: "history")
}

setHistory(0, history: ["history1.1", "history1.2", "history1.3"])
print(userDict)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM