更新字典中的值

时间:2017-11-21 10:45:39

标签: ios swift nsdictionary

我有一个类型[String:Any]()的字典,并且正在添加一个值...

myDictionary["qty"] = "1"

现在qty是我可以从选择器视图更改的数量。因此,如果我从pickerview中选择值3,那么更新后的数量将是3而不是1.我正试图实现这样的目标......

 myDictionary.updateValue(cell.qtyPickerField.text!, forKey: "qty")

 arrayOfDictionary.append(myDictionary)

但是在这里,因为我正在使用append,所以还有一个字典被添加到数组中,数量值为3.但我想要实现的是更新我已经拥有的字典值为3而不是1,而不是添加一个字典,因为我现在正在做。

但是如何才能实现这一点我无法弄明白......

编辑。选择器视图中的代码didSelectRow如下所示......

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if pickerView is MyPickerView {

            if let cell = (pickerView as! MyPickerView).cell {

        cell.qtyPickerField.text = noOfItems[row] // for displaying of nos picker view


  myDictionary.updateValue(cell.qtyPickerField.text!, forKey: "qty")

 arrayOfDictionary.append(self.appDelegate.myDictionary)

        let data = try! JSONSerialization.data(withJSONObject: arrayOfDictionary, options: .prettyPrinted)
                print(data)
        self.appDelegate.jsonValue = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
        print(self.appDelegate.jsonValue)


                }
            }

        }
    }

2 个答案:

答案 0 :(得分:1)

首先从arrayOfDictionary获取字典:

let index : Int = // index for myDictionary
myDictionary = arrayOfDictionary[index]

然后

myDictionary["qty"] = cell.qtyPickerField.text!
arrayOfDictionary[index] = myDictionary

答案 1 :(得分:-3)

swift中的数组/字典是值类型,你想要的是act字典作为引用类型。在您的情况下,使用NSMutableDictionary例如

let dict = NSMutableDictionary()
var array = [NSMutableDictionary]()
dict["qty"] = "1"
array.append(dict)
print("Array has:\(array)")
print("------ Now we'll change the data withoout appending -----")
dict["qty"] = "3"
print("Array has:\(array)")

控制台日志:

Array has:[{
    qty = 1;
}]
------ Now we'll change the data withoout appending -----
Array has:[{
    qty = 3;
}]