ios - 使用唯一键快速合并字典

标签 ios swift dictionary swift4

我正在尝试对具有唯一类型的字典求和-

   let dict1: [String:Any] = ["type":"steps","value": 100]
   let dict2: [String:Any] = ["type":"cal","value": 200]
   let dict3: [String:Any] = ["type":"cal","value": 300]
   let dict4 : [String:Any] = ["type":"steps","value": 400]
   let dict5 : [String:Any] = ["type":"cal","value": 500]

我只是在寻找结果 -

sum is - [["type":"steps","value": 500],["type":"cal","value": 1000]]

我经历了https://developer.apple.com/documentation/swift/dictionary 但没有找到我需要的东西

请帮忙解决这个问题

最佳答案

你可以这样做:

        let dict1: [String:Any] = ["type":"steps","value": 100]
        let dict2: [String:Any] = ["type":"cal","value": 200]
        let dict3: [String:Any] = ["type":"cal","value": 300]
        let dict4 : [String:Any] = ["type":"steps","value": 400]
        let dict5 : [String:Any] = ["type":"cal","value": 500]

        let array = [dict1,dict2,dict3,dict4,dict5]

        let list :[String:[[String:Any]]] = Dictionary(grouping: array, by: {$0["type"] as? String ?? ""})

        let result =  list.map { (key,value) -> [String:Any] in
            let sum = value.reduce(0, {$0 + ($1["value"] as? Int ?? 0)})
            return ["type":key , "value":sum]
        }

        print(result)

输出:

[["type": "cal", "value": 1000], ["type": "steps", "value": 500]]

关于ios - 使用唯一键快速合并字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50506702/

相关文章:

ios - 阻止 TableView backgroundView 越过每个部分的最后一个单元格?

javascript - iOS 中的 Acrobat javascript API

ios - 开始日期、结束日期以及在 ViewController 中向标签添加文本

java - 合并json、java中 map 的数组列表

c# - 从 IEnumerable<Dictionary<string, object>> 获取键和值

ios - 在 Swift 中将数组保存到文件

IOS WKWebView 文件上传不工作

ios - 使用 Core Data 时如何使用 Watch Connectivity 共享数据

swift - Swagger 自动生成不包含错误类

ios - swift 2.0 : Type of Expression is ambiguous without more context?