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

Swift中如何基于另一枚举添加枚举值?解决自定义酒精统计Bug

解决Swift自定义酒精类型的专属容器统计问题

我定义了两个Swift枚举,分别是表示容量类型的AlcoholVolumeType和表示酒精类型的AlcoholType,代码如下:

enum AlcoholVolumeType: String {
    case portion30
    case portion40
    case portion50
    case wineglass100
    case wineglass125
    case wineglass150
    case glass175
    case glass200
    case glass300
    case beerBottle330
    case beerBottle355
    case beerGlass400
    case britishBank440
    case americanPint473
    case beerBottle500
    case britishPint568
    case bomber650
}
enum AlcoholType: String {
    case champagne
    case wineRed
    case wineWhite
    case winePink
    case portWine
    static var wineTypes: [AlcoholType] { [.champagne, .wineRed, .wineWhite, .winePink, .portWine] }
    var isWine: Bool { AlcoholType.wineTypes.contains(self) }
    case beerLight
    case beerDark
    case beerUnfiltered
    case cider
    case ale
}

我的应用支持添加自定义酒精类型,但当两种自定义酒精选择相同容器时,统计功能会出Bug——因为统计是按容器类型计算的,相同容器会被混用。我尝试用case \(AlcoholType)wineglass150的写法给AlcoholVolumeType添加枚举值,结果报错“Consecutive declarations on a line must be separated by ';'”,请问该怎么正确实现?


可行解决方案

方案1:把容量枚举改成带关联值的类型

Swift枚举的case是静态定义的,不能用字符串插值动态生成。最直接的办法是给AlcoholVolumeType新增一个带关联值的case,把酒精类型绑定进去,这样每个容器实例都能对应专属的酒精类型:

enum AlcoholVolumeType: String {
    // 保留原有所有容量case
    case portion30
    case portion40
    case portion50
    case wineglass100
    case wineglass125
    case wineglass150
    case glass175
    case glass200
    case glass300
    case beerBottle330
    case beerBottle355
    case beerGlass400
    case britishBank440
    case americanPint473
    case beerBottle500
    case britishPint568
    case bomber650
    
    // 新增自定义专属容器case,关联酒精类型和容量值
    case custom(type: AlcoholType, volume: Int)
}

// 使用示例:给自定义酒精类型创建专属容器
let customFruitWineGlass = AlcoholVolumeType.custom(type: .customFruitWine, volume: 150)

统计时,只要同时读取关联的酒精类型和容量,就能区分不同酒精的相同容器,不会再混用。

方案2:用结构体组合酒精类型与容器类型

如果不想修改原有枚举,可以单独定义一个结构体,把酒精类型和容器类型打包成一个单元,作为统计的最小单位:

// 假设你已经扩展了AlcoholType支持自定义case
extension AlcoholType {
    case customFruitWine
    case customCraftBeer
}

struct AlcoholContainer {
    let alcoholType: AlcoholType
    let volumeType: AlcoholVolumeType
}

// 使用示例:创建不同酒精类型的相同容器实例
let redWine150 = AlcoholContainer(alcoholType: .wineRed, volumeType: .wineglass150)
let customFruitWine150 = AlcoholContainer(alcoholType: .customFruitWine, volumeType: .wineglass150)

统计时以AlcoholContainer为维度进行计算,自然就能区分开不同酒精的相同容器。

方案3:提前定义所有组合(不推荐)

如果非要用纯枚举的方式,只能在编译时提前把所有酒精类型和容器类型的组合都定义成case,但这种方式完全不支持动态添加自定义酒精类型,所以不适合你的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:05:32