基本上,我有一个 NSarray
的 dictionaries
作为 JSON 响应仅在 View 出现时出现一次。现在,我需要每隔几秒用另一组字典更新这些字典中某个键的特定值,这样我就可以用这些值连续更新我的字典数组,并在屏幕上显示一些实时数据集。
示例:这是我从后端获取的字典数组
[
{item_id: 1001, name: "Apple", current_price: "$10"},
{item_id: 1009, name: "Orange", current_price: "$15"},
{item_id: 1004, name: "Mango", current_price: "$5"}
]
当前价格是不断变化的,我分别以 NSDictionary
格式接收其数据。
["1009": "$16", "1004": "$3", "1001": "$11"]
如您所见,新的 NSDictionary
与 item_id
映射到当前价格值。
我需要一种方法来确保当前价格从这个 NSDictionary
更新到字典数组,以便我可以重用该数组来重新加载我的 UITableview
和显示更新的实时价格。
最佳答案
你可以这样做:
let items = [["item_id": 1001, "name": "Apple", "current_price": "$10"], ["item_id": 1009, "name": "Orange", "current_price": "$15"], ["item_id": 1004, "name": "Mango", "current_price": "$5"]]
let prices = ["1009": "$16", "1004": "$3", "1001": "$11"]
let updatedItems = items.map { itemDict -> [String: Any] in
var updatedItem = itemDict
if let idKey = itemDict["item_id"] as? Int {
prices["\(idKey)"].flatMap { updatedItem["current_price"] = $0 }
}
return updatedItem
}
关于ios - Swift - 使用另一个 NSDictionary 的值更新 NSDictionary 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46377270/