bra*_*ipt 1 switch-statement swift
我知道在 Swift 中我可以做一个简单的 Swift switch 语句来将计算值与单个变量进行比较:
let distanceTravelled = -145.1
switch distanceTravelled {
case _ where distanceTravelled < 15:
print("You travelled the right distance")
default:
print("Sad face")
}
Run Code Online (Sandbox Code Playgroud)
但我希望能够使用元组设置比较矩阵,如下所示:
let distanceTravelled = -145.1,
origin = 2
switch (origin, distanceTravelled) {
case (2, _ where distanceTravelled < 15):
print("You travelled the right distance")
default:
print("Sad face")
}
Run Code Online (Sandbox Code Playgroud)
但这不能编译,抱怨expected ',' separator和expected expression in list of expressions。
显然这在语法上是不正确的,但是考虑到它是有效的,它不应该有效吗?
switch (2, -145.1) {
case (2, _):
print("You travelled the right distance")
default:
print("Sad face")
}
Run Code Online (Sandbox Code Playgroud)
啊哈!在优秀的Swift 文档中找到了答案。我并没有从元组的条件来考虑这一点。
switch (origin, distanceTravelled) {
case let (_, d) where d < 15:
print("You travelled the right distance")
default:
print("Sad face")
}
Run Code Online (Sandbox Code Playgroud)
对于我的实际用例,这有点奇怪,因为我正在比较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
}
Run Code Online (Sandbox Code Playgroud)
奇怪的是,在进一步简化过程中,我什至不需要在前两次检查中声明变量:
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2699 次 |
| 最近记录: |