You need to enable JavaScript to run this app. Swift如何简化批量检查数组包含字符串的重复if let判断逻辑
优惠活动
大模型
产品
解决方案
定价
更多

Swift如何简化批量检查数组包含字符串的重复if let判断逻辑

优化实现方案

核心思路是将一一对应的编码、文本数组转换为键值映射表,统一解包可选值后批量完成校验,彻底消除重复的if let代码。


前置步骤:构建映射关系

首先把两个独立数组合并为字典,方便后续快速查找:

// 方式1:从已有数组转换
let codeTextMap = Dictionary(uniqueKeysWithValues: zip(code, text))

// 方式2:如果映射关系固定,推荐直接写死字典,更易维护
/*
let codeTextMap: [String: String] = [
    "MDLS": "Tesla Model S",
    "MS03": "Tesla Model S",
    "MS04": "Tesla Model S",
    "MDLX": "Tesla Model X",
    "MDL3": "Tesla Model 3",
    "MDLY": "Tesla Model Y"
]
*/

方案1:完全对齐原有逻辑(全量校验,后匹配项覆盖前值)

和你现有逻辑完全一致,会遍历所有编码打印校验结果,多个编码同时匹配时后面的匹配结果会覆盖myString的取值:

// 先统一解包optionCodes,避免重复可选绑定
guard let optionCodes = data[indexPath.row].optionCodes else {
    print("optionCodes为空")
    return
}

var myString = ""
for (code, text) in codeTextMap {
    if optionCodes.contains(code) {
        print("Yes, optionCodes contains \(code)")
        myString = text
    } else {
        print("No")
    }
}

方案2:高性能优化版(匹配到首个符合项即停止)

如果不需要打印所有编码的校验结果,只需要拿到第一个匹配的文本,推荐用这个方案,执行效率更高:

guard let optionCodes = data[indexPath.row].optionCodes else {
    print("optionCodes为空")
    return
}

var myString = ""
// 按原有code数组的顺序查找第一个匹配的编码
if let matchedCode = code.first(where: { optionCodes.contains($0) }),
   let matchedText = codeTextMap[matchedCode] {
    print("Yes, optionCodes contains \(matchedCode)")
    myString = matchedText
} else {
    print("无匹配编码")
}

注意事项

如果存在多个编码同时出现在optionCodes中的情况,code数组的顺序决定了优先匹配的规则,需要和你原有if判断的顺序保持一致,避免逻辑不一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 16:33:02