【问题标题】:Swift switch matching multiple conditionalsSwift switch 匹配多个条件
【发布时间】:2018-01-19 21:14:21
【问题描述】:

由于case: 阻止自动中断,Swift 提供了 fallthrough 关键字。这是有限的用途,因为它不会进入下一个条件测试,它会绕过下一个测试并只执行下一个测试中的代码。是否可以让 switch 语句在多个情况下执行代码同时执行条件?

作为 Swift 文档中的示例,如果我需要下面的代码来执行适用于给定点的每个块怎么办?

let somePoint = (0, 0)
switch somePoint {
case (0, 0):
    print("\(somePoint) is at the origin")
case (_, 0):
    print("\(somePoint) is on the x-axis")
case (0, _):
    print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
    print("\(somePoint) is inside the box")
default:
    print("\(somePoint) is outside of the box")
}

即使实际应用了多个,它也只会打印第一个描述。在每次测试后使用 fallthrough 会导致每个 case 块都执行。

【问题讨论】:

  • 这不是 switch 语句的用途——你可以使用多个 if 语句。
  • 当然,用 if 语句来做这件事要丑得多。如果有类似 fallthroughAndTest 的东西,那就太好了。 Swift 开关已经非常强大了,我希望有一种技术可以做到这一点。
  • 我认为没有。
  • 这是一个有趣的想法。 switch 曾经是一个排他结构,其中一个值与一组确定的案例进行比较。在这种情况下,“fallthroughAndTest”将没有意义,因为测试总是会失败(例如,如果整数 i 匹配 case 0,则可以保证对 case 1 的测试失败)。所以只有fallthrough 才有意义,但现在排他性限制已经解除,引入这样的新结构是有意义的

标签: swift switch-statement


【解决方案1】:

switch 语句将值与模式进行比较并执行 基于第一次成功匹配的代码。

如果您的意图是匹配多个模式并执行 所有匹配的代码然后使用多个 if 语句。 可以使用相同的案例模式:

if case (0, 0) = somePoint {
    print("\(somePoint) is at the origin")
}
if case (_, 0) = somePoint {
    print("\(somePoint) is on the x-axis")
}
// ...
if case (-2...2, -2...2) = somePoint {
    print("\(somePoint) is inside the box")
}
// ...

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-12-28
  • 2014-09-11
  • 1970-01-01
  • 2022-01-11
  • 2021-03-04
  • 2019-10-22
  • 2020-10-27
  • 2021-01-08
相关资源
最近更新 更多