我正在使用 swift,在使用 switch 语句和大于 > 比较数字时遇到错误。
Xcode 显示以下消息:“Bool”类型的表达式模式无法匹配“Int”类型的值
我知道通过替换 case self > 0: return .positive
与 case let x where x > 0: return .positive
,一切正常。
但我不太明白为什么case self > 0: return .positive
不允许?其背后的原因是什么?
extension Int {
enum Kind {
case negative, zero, positive
}
var kind: Kind {
switch self {
case 0:
return .zero
//Error: expression pattern of type "Bool" cannot match values of type "Int"
// case self > 0:
// return .positive
case let x where x > 0: //this works
return .positive
default:
return .negative
}
}
}
最佳答案
这是一个关于 switch 语句的简单规则。
在每个 switch 语句的 case 中,紧跟在 case
之后的表达式被求值并与你正在打开的东西进行比较。
因此在您的代码中,self > 0
被计算并与 self
进行比较。假设 self
为 10,
self > 0 == self
true == 10 // WTF?
第二种case let x where x > 0
不同,let x
不是表达式。它基本上说:
In this
case
, I want a variable calledx
to be assigned the value ofself
. But please only do this ifx > 0
after doing the assignment. If!(x > 0)
, go to anothercase
.
关于ios - 为什么 switch 语句中不允许使用 `case self > 0: return .positive`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40124019/