如何使用字典对同一键的值求和?

时间:2019-12-05 00:23:22

标签: swift sorting dictionary

我有一本字典,看起来像这样:

(value: 21.0, id: "JdknnhshyrY56AXQcAiLcYtbVlz2") ---> This has a second entry
(value: 18.0, id: "nIvb519nNfMtlVNnsQJ5w4bRbFp2")
(value: 14.0, id: "tlKqcxHdPoemwGqJsyLhERnuQ3Z2")
(value: 5.0,  id: "JdknnhshyrY56AXQcAiLcYtbVlz2")]---> This is the second entry

如果条目重复,我想将值添加到相同的ID。 像这样:

(value: 26.0, id: "JdknnhshyrY56AXQcAiLcYtbVlz2") ---> Value has added and key has become only one
(value: 18.0, id: "nIvb519nNfMtlVNnsQJ5w4bRbFp2")
(value: 14.0, id: "tlKqcxHdPoemwGqJsyLhERnuQ3Z2")]

我已经尝试过使用map方法,但是一直在工作,已经添加了值,但id上的多个条目仍然保持一个以上。

如何获得结果。

1 个答案:

答案 0 :(得分:1)

  

始终建议您转换Dictionary(使用异构   最终属于[AnyHashable : Any]的值的类型   类别)添加到 Typed 对象。对于键入的对象,操纵或   其他计算变得很方便。

在上述声明的前提下,您将执行以下操作:

let objects = [Object]() // this would be you array with actual data
let reduced = objects.reduce(into: [Object]()) { (accumulator, object) in
    if let index = accumulator.firstIndex(where: { $0.id == object.id }) {
        accumulator[index].value += object.value
    } else {
        accumulator.append(object)
    }
}

Object所在的位置:

struct Object {
    var value: Double
    let id: String
}

现在,如果您想知道如何将Dictionary类型转换为&Object类型,请查看完整的代码:

let arrayOfDictionary = [["value": 21.0, "id": "JdknnhshyrY56AXQcAiLcYtbVlz2"],
                         ["value": 18.0, "id": "nIvb519nNfMtlVNnsQJ5w4bRbFp2"],
                         ["value": 14.0, "id": "tlKqcxHdPoemwGqJsyLhERnuQ3Z2"],
                         ["value": 5.0,  "id": "JdknnhshyrY56AXQcAiLcYtbVlz2"]]

struct Object: Codable {
    var value: Double
    let id: String
}

do {
    let jsonData = try JSONSerialization.data(withJSONObject: arrayOfDictionary, options: [])
    let objects = try JSONDecoder().decode([Object].self, from: jsonData)

    let reduced = objects.reduce(into: [Object]()) { (accumulator, object) in
        if let index = accumulator.firstIndex(where: { $0.id == object.id }) {
            accumulator[index].value += object.value
        } else {
            accumulator.append(object)
        }
    }

    let encodedObjects = try JSONEncoder().encode(reduced)
    let json = try JSONSerialization.jsonObject(with: encodedObjects, options: [])
    if let reducedArrayOfDictionary = json as? [[String : Any]] {
        print(reducedArrayOfDictionary)
    }
} catch {
    print(error)
}