Swift 4 switch语句比较多个值,使用大于或小于

时间:2017-09-02 00:18:10

标签: swift switch-statement

我知道在Swift中我可以做一个简单的Swift switch语句来比较计算值和单个变量:

let distanceTravelled = -145.1
switch distanceTravelled {
case _ where distanceTravelled < 15:
    print("You travelled the right distance")
default:
    print("Sad face")
}

但我希望能够使用元组建立比较矩阵,如下所示:

let distanceTravelled = -145.1,
    origin = 2

switch (origin, distanceTravelled) {
case (2, _ where distanceTravelled < 15):
    print("You travelled the right distance")
default:
    print("Sad face")
}

但这并没有编译,抱怨expected ',' separatorexpected expression in list of expressions

显然这在语法上是不正确的,但鉴于这有效,它不应该起作用吗?

switch (2, -145.1) {
case (2, _):
    print("You travelled the right distance")
default:
    print("Sad face")
}

1 个答案:

答案 0 :(得分:2)

啊哈!找到了良好的答案&#39; Swift docs。就条件是一个元组而言,我并没有想到这一点。

switch (origin, distanceTravelled) {
case let (_, d) where d < 15:
    print("You travelled the right distance")
default:
    print("Sad face")
}

对于我的实际用例,这有点奇怪,因为我正在比较enum属性的原点,但它确定了:

let absOriginDistanceFromDefault = abs(defaultDividerPosition - viewDividerOrigin)

switch (splitViewOrigin, distanceTravelled) {
case let (.defaultPosition, d) where d < -100:
    return .shouldMoveToTopView
case let (.defaultPosition, d) where d > 100:
    return .shouldMoveToBottomView
case (.topView, _) where currentDividerPosition - defaultDividerPosition < -100:
    return .shouldMoveToBottomView
case (.topView, _) where abs(distanceTravelled) > absOriginDistanceFromDefault * 0.5 && currentDividerPosition < self.view.bounds.height:
    return .shouldMoveToDefaultPosition
case (.bottomView, _) where currentDividerPosition - defaultDividerPosition > 100:
    return .shouldMoveToTopView
case (.bottomView, _) where abs(distanceTravelled) > absOriginDistanceFromDefault * 0.3 && currentDividerPosition > 0:
    return .shouldMoveToDefaultPosition
default:
    return .shouldReturnToOrigin
}

奇怪的是,在进一步简化它时,事实证明我甚至不需要在前两个检查中声明变量:

let absOriginDistanceFromDefault = abs(defaultDividerPosition - viewDividerOrigin)

switch (splitViewOrigin, distanceTravelled) {
case (.defaultPosition, _) where distanceTravelled < -100,
     (.bottomView, _) where currentDividerPosition - defaultDividerPosition > 100:
    return .shouldMoveToTopView
case (.defaultPosition, _) where distanceTravelled > 100,
     (.topView, _) where currentDividerPosition - defaultDividerPosition < -100:
    return .shouldMoveToBottomView
case (.topView, _) where abs(distanceTravelled) > absOriginDistanceFromDefault * 0.5 && currentDividerPosition < maxHeight,
     (.bottomView, _) where abs(distanceTravelled) > absOriginDistanceFromDefault * 0.3 && currentDividerPosition > 0:
    return .shouldMoveToDefaultPosition
default:
    return .shouldReturnToOrigin
}