gpt4 book ai didi

swift - 是否可以在枚举关联值条件和另一个枚举案例之间编写复合切换案例?

转载 作者:搜寻专家 更新时间:2023-10-31 21:55:59 24 4
gpt4 key购买 nike

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

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。正如我已经在谷歌上搜索到的那样,使用关联值的一种方法是比较同一枚举案例中值的不同状态。但这可能会导致代码重复,就像在我的示例中一样,我需要为 .sunny.cloudy(let coverage) 编写两个 case 语句,其中 coverage == 0 .

有没有正确、快捷的方法来处理这种情况?

最佳答案

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

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

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

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

关于swift - 是否可以在枚举关联值条件和另一个枚举案例之间编写复合切换案例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56482153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com