[英]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.