func buttonAction(sender:radioButton!) {
let tempGetTestDesc = dspResult[sender.indexPathSection!]["tests"] as! NSMutableDictionary
let temp = tempGetTestDesc["tests"]as! NSMutableArray
var tem = temp[sender.indexPathRow!] as! Dictionary<String, AnyObject>
switch sender.tag{
case 110:
tem["sideValue"] = "Left"
case 111:
tem["sideValue"] = "Right"
case 112:
tem["sideValue"] = "Both"
case 113:
tem["contrastValue"] = "Y"
default:
break
}
它不会导致上述代码出错。但是它没有更新dspResult中的值。它只更新tem内的值。所以我使用以下代码来更新值。
(((dspResult[sender.indexPathSection!]["tests"] as! NSMutableDictionary)["tests"]as! NSMutableArray)[sender.indexPathRow!] as! Dictionary<String, AnyObject>)["contrastValue"] = "Y"
但是,它不起作用。无法分配类型为
的不可变表达式答案 0 :(得分:0)
原因是你将tem变量打开为Dictionary
,swift中的Dictionary
是value type
,这意味着,任何变量赋值都会导致创建一个新的字典对象并赋值变量,而不是引用赋值。
func buttonAction(sender:radioButton!) {
let tempGetTestDesc = dspResult[sender.indexPathSection!]["tests"] as! NSMutableDictionary
let temp = tempGetTestDesc["tests"]as! NSMutableArray
var tem = temp[sender.indexPathRow!] as! NSMutableDictionary // <--- Instead of Dictionary
switch sender.tag{
case 110:
tem["sideValue"] = "Left"
case 111:
tem["sideValue"] = "Right"
case 112:
tem["sideValue"] = "Both"
case 113:
tem["contrastValue"] = "Y"
default:
break
}
您可以将以下代码复制并粘贴到游乐场,您就会明白我的意思。
let a = NSMutableDictionary(dictionary: ["a": 1])
let aa = NSMutableArray(array: [a])
var b = aa[0] as! Dictionary<String, AnyObject> // <-- b is a new copy of a dictionary, so change the value in b, will not impact to the variable a
b["a"] = 2
print(a["a"]!)
let c = aa[0] as! NSMutableDictionary // <--- c is reference to the origin dictionary a, so changing the value in c will change the value in a
c["a"] = 2
print(a["a"]!)