swift - 是否可以在枚举关联值条件和另一个枚举案例之间编写复合开关案例?
问题描述
出于演示目的,我创建了下一个代码:
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
and编写两个 case 语句.cloudy(let coverage) where coverage == 0
。
有没有正确、快捷的方式来处理此类案件?
解决方案
您不需要 where-clause 来匹配.cloudy(coverage: 0)
,只需
case .cloudy(coverage: 0), .sunny:
print("☀️")
另一种选择是使用fallthrough
,例如
case .cloudy(let coverage) where coverage < 10:
fallthrough
case .sunny:
print("☀️")
推荐阅读
- python - 有没有一种简单的方法可以递归地将 __name__ 添加到 MagicMock 属性中
- kubernetes - Kubernetes 处理处理能力的突然请求(例如使用 5 个进程的 Python 脚本)
- node.js - 如何设置我的后端服务器而不在每次重新启动时重写数据
- scala - Building Scala project with docker's Multi-Stage
- testing - Cypress.io with Testcafe
- linux - Calculate last day of quarter with date binary in a simpler/better way
- python - How do I tell a .py script to look for folders and file in the directory it is in?
- django - Django 用子查询分组查询集
- javascript - Ajax doesn't do anything when php connected to database
- javascript - JS/Docker - Property 'user' does not exist on type 'Session & Partial
'