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

如何在Swift中对分组后的DailyContractorsSummary同时求和oPTime与lostTime

解决方案:同时对两个字段分组求和

修改后的代码实现

// 按rigOperator分组,同时计算每组的lostTime和oPTime总和
let filteredDailyContractorsSummary = Dictionary(grouping: Variables.dailyContractorsSummary) { $0.rigOperator }
    .mapValues { recordsGroupedByRigOperator in
        // 一次遍历完成两个字段的累加,性能更优
        recordsGroupedByRigOperator.reduce((totalLostTime: 0, totalOPTime: 0)) { accumulator, record in
            (
                totalLostTime: accumulator.totalLostTime + record.lostTime,
                totalOPTime: accumulator.totalOPTime + record.oPTime
            )
        }
    }
    .map { key, summedValues in
        // 替换为你实际使用的结构体,确保它支持lostTime和oPTime字段
        FilteredDailyContractorsSummary(
            rigOperator: key,
            lostTime: summedValues.totalLostTime,
            oPTime: summedValues.totalOPTime,
            efficiency: 0 // 如需计算efficiency可在此添加逻辑,比如(totalOPTime/(totalOPTime+totalLostTime))等
        )
    }

关键修改点

  1. 调整mapValues返回值:不再只返回单个字段的求和结果,改为返回包含totalLostTime和totalOPTime的元组,同时完成两个字段的累加。
  2. 高效累加逻辑:用reduce一次遍历分组后的数组,同时累加两个字段,避免多次遍历的性能损耗。
  3. 适配目标结构体:确保最终映射的结构体(示例中为FilteredDailyContractorsSummary)包含lostTime和oPTime字段,用于存储分组求和结果。

备选直观写法(多一次遍历)

如果觉得reduce的写法不够直观,也可以用先map再reduce的方式:

.mapValues { records in
    let totalLostTime = records.map(\.lostTime).reduce(0, +)
    let totalOPTime = records.map(\.oPTime).reduce(0, +)
    return (totalLostTime: totalLostTime, totalOPTime: totalOPTime)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 18:44:55