我有一个像这样的字典数组......
[
{
"sellingPrice" : "200",
"transaction_id" : "COD",
"shipping_charges" : "",
"id" : "3",
"payment_method" : "",
"taxes" : "0",
"applied_coupon_code" : "",
"discount_price" : "",
"quantity" : "13",
"transaction_type" : "COD",
"remaining_balance" : "",
"grand_total" : ""
},
{
"sellingPrice" : "200",
"transaction_id" : "COD",
"shipping_charges" : "",
"id" : "22",
"payment_method" : "",
"taxes" : "0",
"applied_coupon_code" : "",
"discount_price" : "",
"quantity" : "3",
"transaction_type" : "COD",
"remaining_balance" : "",
"grand_total" : ""
}
]
我有一个名为“部分金额”的东西,值为 50。现在,我想遍历字典数组,检查 partial amount
是否小于 sellingPrice
,如果小于,则从中减去 partial amount
,结果值将分配给键 remaining_balance
所以在这种情况下,将从 200 的第一个 sellingPrice
中减去 50,得到第一个字典的 remaining_balance
的值为 150。因为现在什么都没有了剩余的 partial amount
50 因为它已经完全用完,第二个 remaining_balance
的 sellingPrice
的值为 200。所以第一个 remaining_balance
将为 150,第二个 remaining_balance
将为 200。
这是我到目前为止尝试过的方法..但它似乎不起作用...
for (index, dict) in self.appDelegate.arrayOfDictionary.enumerated() {
for element in dict {
if element.key == "sellingPrice" {
let PAinTxtField = alertController.textFields?.first?.text)!
var thePA = (Int(PAinTxtField ) ?? 0) //This is partial amount
let theSP = (Int("\(element.value)") ?? 0) //This is selling price
if thePA < theSP {
self.remainingAmt = theSP - thePA
var dictCopy = dict
dictCopy["remaining_balance"] = "\(self.remainingAmt)" //The mistake seems to be because of this line. But cannot figure out what exactly...:(
}
}
}
}
最佳答案
试试这个:
self.appDelegate.arrayOfDictionary[index] = dictCopy //replace new copyDict with old dict
关于swift - 为字典中的键分配值的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47216495/