ios - Swift - 使用另一个 NSDictionary 的值更新 NSDictionary 数组

标签 ios arrays swift parsing nsdictionary

基本上,我有一个 NSarraydictionaries 作为 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"]

如您所见,新的 NSDictionaryitem_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/

相关文章:

ios - 重用 UIWebView 导致崩溃

ios - 更新到 iOS 14 和 Xcode 12 后应用启动时间变慢

ios - 灵活的 ImageView

javascript - JS/jQuery : Filter object properties by array

swift - 如何在主体 View 中设置对齐方式?

swift - 用于对象搜索的 CoreML

ios - EXC_BAD_ACCESS KERN_INVALID_ADDRESS 在 Swift 和 iPhone 5 中

iphone - 对二维数组进行排序

javascript - 简单的查找和更新记录功能......我无法工作

属性后的 Swift 括号表示法