Swift中如何统计数组内important和urgent两个字段的组合出现次数
我们可以通过预设四种状态组合的初始计数字典,遍历entry数组累加计数的方式实现需求,既可以覆盖全部组合场景,也能保证出现次数为0的组合正常输出:
// 初始化统计字典,预设四种组合初始计数为0 var statResult: [String: Int] = [ "important & urgent": 0, "important & none": 0, "none & urgent": 0, "none & none": 0 ] // 遍历任务数组累加计数 for task in entry { // 统一转小写避免大小写不匹配问题,若字段本身为全小写可省略该步骤 let impVal = task.important.lowercased() let urgVal = task.urgent.lowercased() let combinationKey = "\(impVal) & \(urgVal)" // 校验key合法性,避免非法字段值导致崩溃 guard statResult.keys.contains(combinationKey) else { continue } statResult[combinationKey]! += 1 }
如果需要按指定对齐格式输出结果,可添加以下代码:
print("即:") print(String(format: "%@ = %d, %@ = %d,", "important & urgent", statResult["important & urgent"]!, "important & none", statResult["important & none"]!)) print(String(format: "%@ = %d, %@ = %d", " none & urgent", statResult["none & urgent"]!, " none & none", statResult["none & none"]!))
输出示例:
即:
important & urgent= 3,important & none= 2,none & urgent= 0,none & none= 4
内容的提问来源于stack exchange,提问作者EddieF
相关产品推荐
相关产品推荐

