You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 5中如何合并数组中属性相同的元素并累加对应属性

Swift 合并数组中属性相同的元素并累加对应属性

首先确保Manipulation结构体已正确定义:

struct Manipulation {
    let productName: String
    let responsibleName: String
    let grossWeight: Double
    let cleanWeight: Double
}

接下来使用reduce结合字典实现分组累加逻辑:

let manipulations: [Manipulation] = [
    .init(productName: "Beer", responsibleName: "John", grossWeight: 100.00, cleanWeight: 30.00),
    .init(productName: "Beer", responsibleName: "John", grossWeight: 200.00, cleanWeight: 50.00),
    .init(productName: "Food", responsibleName: "Michael", grossWeight: 100.00, cleanWeight: 20.00),
    .init(productName: "Food", responsibleName: "Michael", grossWeight: 400.00, cleanWeight: 100.00),
    .init(productName: "Object", responsibleName: "John", grossWeight: 400.00, cleanWeight: 100.00),
    .init(productName: "Beer", responsibleName: "John", grossWeight: 200.00, cleanWeight: 50.00),
    .init(productName: "Beer", responsibleName: "John", grossWeight: 200.00, cleanWeight: 50.00),
    .init(productName: "Beer", responsibleName: "John", grossWeight: 200.00, cleanWeight: 50.00),
    .init(productName: "Water", responsibleName: "John", grossWeight: 200.00, cleanWeight: 50.00)
]

// 分组并累加重量
let groupedDict = manipulations.reduce(into: [ (String, String): Manipulation ]()) { dict, item in
    let key = (item.productName, item.responsibleName)
    if let existingItem = dict[key] {
        // 累加重量后创建新实例
        let updatedItem = Manipulation(
            productName: item.productName,
            responsibleName: item.responsibleName,
            grossWeight: existingItem.grossWeight + item.grossWeight,
            cleanWeight: existingItem.cleanWeight + item.cleanWeight
        )
        dict[key] = updatedItem
    } else {
        // 首次出现该分组,直接存入字典
        dict[key] = item
    }
}

// 转换为数组得到最终结果
let mergedManipulations = Array(groupedDict.values)

// 打印验证结果
print(mergedManipulations)

逻辑说明

  • 以(productName, responsibleName)元组作为分组标识,确保只有两个属性完全匹配的元素才会被归为一组
  • 遍历数组时,若当前分组已存在则累加重量并更新字典;若不存在则直接存入
  • 最后将字典的值转为数组,即为合并后的目标结果

内容的提问来源于stack exchange,提问作者setropjp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 03:43:08