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

如何替换Switch语句以降低代码圈复杂度(CCN)?

替换Swift中Switch语句降低圈复杂度的可行方案

针对你遇到的Sonar检测提示Switch语句提升圈复杂度的问题,这里提供两种实用的替换方案:

方案一:给ItemType枚举添加计算属性

直接把每个枚举值对应的Segue关联到枚举内部,将复杂度封装在枚举里,外部调用逻辑极度简化:

enum ItemType {
    case one, two, three, four, five, six, seven, eight, nine, ten
    
    // 新增计算属性,返回对应Segue标识
    var segueIdentifier: StoryboardSegue {
        switch self {
        case .one: return .One
        case .two: return .Two
        case .three: return .Three
        case .four: return .Four
        case .five: return .Five
        case .six: return .Six
        case .seven: return .Seven
        case .eight: return .Eight
        case .nine: return .Nine
        case .ten: return .Ten
        }
    }
}

func handleNavigation(itemType: ItemType){
    self.performSegue(withIdentifier: itemType.segueIdentifier, sender: nil)
}

后续新增枚举值时,只需要在枚举的计算属性里补充对应关系即可,外部调用代码无需修改。

方案二:使用字典映射关系

提前建立ItemType到StoryboardSegue的映射字典,完全消除Switch语句,将圈复杂度降到最低:

enum ItemType {
    case one, two, three, four, five, six, seven, eight, nine, ten
}

// 定义映射字典(可放在类内部或全局)
private let itemSegueMap: [ItemType: StoryboardSegue] = [
    .one: .One,
    .two: .Two,
    .three: .Three,
    .four: .Four,
    .five: .Five,
    .six: .Six,
    .seven: .Seven,
    .eight: .Eight,
    .nine: .Nine,
    .ten: .Ten
]

func handleNavigation(itemType: ItemType){
    guard let segue = itemSegueMap[itemType] else {
        // 可在这里处理未找到对应Segue的异常场景
        return
    }
    self.performSegue(withIdentifier: segue, sender: nil)
}

这种方案扩展性极强,新增ItemType时只需在映射字典里添加新的键值对,还能通过guard语句做安全校验,避免无效导航。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:35:54