首页 > 解决方案 > 是否可以在枚举关联值条件和另一个枚举案例之间编写复合开关案例?

问题描述

出于演示目的,我创建了下一个代码:

enum WeatherType {
    case cloudy(coverage: Int)
    case sunny
    case rainy
}

let today: WeatherType = .cloudy(coverage: 0)

switch today {
case .cloudy(let coverage) where coverage == 0, .sunny:   // <-- This line doesn't compile
    print("☀️")
case .cloudy(let coverage) where 1...100 ~= coverage:
    print("☁️")
case .rainy:
    print("")
default:
    print("Unknown weather")
}

编译错误消息是'coverage' must be bound in every pattern。正如我已经在谷歌上搜索到的那样,使用关联值的一种方法是比较同一枚举案例中值的不同状态。但这可能会导致代码重复,例如在我的示例中,我需要为.sunnyand编写两个 case 语句.cloudy(let coverage) where coverage == 0

有没有正确、快捷的方式来处理此类案件?

标签: swiftenums

解决方案


您不需要 where-clause 来匹配.cloudy(coverage: 0),只需

case .cloudy(coverage: 0), .sunny: 
    print("☀️")

另一种选择是使用fallthrough,例如

case .cloudy(let coverage) where coverage < 10:
    fallthrough
case .sunny:
    print("☀️")

推荐阅读