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

Swift中合并多个字典生成FoundDevice自定义对象数组的更优实现方法

实现方案1:使用compactMap简化写法(推荐)

你的原有逻辑是正确的,用compactMap替代forEach+手动追加数组的写法更简洁,同时省去一次可选绑定:

let devices = serialsDict.compactMap { source, serial in
    guard let name = namesDict[source],
          let fwVersion = fwVersionsDict[source],
          let hwVersion = hwVersionDict[source],
          let type = typesDict[source] else { return nil }
    return FoundDevice(
        source: source,
        serial: serial,
        name: name,
        fwVersion: fwVersion,
        hwVersion: hwVersion,
        type: type
    )
}

优势:

  • 直接生成不可变数组,无需提前声明可变容器,代码更安全
  • 直接复用serialsDict遍历出的serial值,省掉一次字典查找,性能微幅提升
  • 语义清晰,符合Swift函数式编程习惯

实现方案2:取Key交集后批量生成(适合字典Key不完全对齐的场景)

如果你不确定5个字典的Key完全一致,想取所有字典的公共Key构建设备,可以先计算Key的交集,再批量生成:

// 计算所有字典的公共Key
let commonKeys = Set(serialsDict.keys)
    .intersection(namesDict.keys)
    .intersection(fwVersionsDict.keys)
    .intersection(hwVersionDict.keys)
    .intersection(typesDict.keys)

let devices = commonKeys.map { source in
    FoundDevice(
        source: source,
        serial: serialsDict[source]!,
        name: namesDict[source]!,
        fwVersion: fwVersionsDict[source]!,
        hwVersion: hwVersionDict[source]!,
        type: typesDict[source]!
    )
}

优势:

  • 自动过滤掉仅在部分字典中存在的Key,不会出现缺字段的问题
  • 提前过滤公共Key后,后续的强制解包是完全安全的,不会崩溃
  • 数据量大时性能优于逐个判断可选值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:45:02