Changing a dictionary property inside an array of dictionaries. Error: Cannot assign immutable expression like [String: AnyObject]

There are several posts on SO like this , and the only solution that seems to work is to manually delete and insert a property with the same index.

But this seems messy, and some reports indicate that in Xcode 7 it is possible to directly update dictionary properties if inside an array of dictionaries.

However, it does not work for the code below, generating a 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 } 

All four lines inside setHistory try to do the same, and all fail.

0
source share
2 answers

Right now, how are you doing this: userDict["accounts"] as! [[String:AnyObject]])[index]["history"] userDict["accounts"] as! [[String:AnyObject]])[index]["history"] you are working with an immutable container.

You will need 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 } 
+1
source

I think you better model your data with a class.

Anyway, you can call an old friend from 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) 
0
source

Source: https://habr.com/ru/post/1238709/


All Articles