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

Swift中如何简化枚举多case的匹配判断?

简化枚举case判断的几种方案

你试的写法报错是因为Swift逻辑运算符两侧必须是布尔值,type == .A1返回Bool,但.A2是枚举值,类型不匹配导致报错。下面给你几个可行的简化方案:

方案1:集合包含判断

把A系列case放进集合,直接判断当前type是否在集合内,代码更简洁:

struct myStruct {
    public var type: Type = .A1

    func isA() -> Bool {
        return [.A1, .A2, .A3].contains(type)
    }
}

方案2:给枚举封装判断属性

把判断逻辑放到枚举内部,结构体直接调用枚举属性,更符合封装思想:

public enum Type { 
    case A1, A2, A3
    case B1, B2
    case C1, C2, C3, C4, C5, C6

    var isA: Bool {
        switch self {
        case .A1, .A2, .A3: return true
        default: return false
        }
    }
}

struct myStruct {
    public var type: Type = .A1

    func isA() -> Bool {
        return type.isA
    }
}

甚至可以直接去掉结构体里的isA()方法,外部直接调用myStructInstance.type.isA,进一步精简代码。

方案3:结构体内部用多case switch

如果不想修改枚举,也可以在结构体方法里用switch的多case匹配,比一堆||更清晰:

struct myStruct {
    public var type: Type = .A1

    func isA() -> Bool {
        switch type {
        case .A1, .A2, .A3: return true
        default: return false
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 00:09:55