gpt4 book ai didi

ios - 为什么 switch 语句中不允许使用 `case self > 0: return .positive`

转载 作者:行者123 更新时间:2023-11-28 09:54:04 25 4
gpt4 key购买 nike

我正在使用 swift,在使用 switch 语句和大于 > 比较数字时遇到错误。

Xcode 显示以下消息:“Bool”类型的表达式模式无法匹配“Int”类型的值

我知道通过替换 case self > 0: return .positivecase 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 called x to be assigned the value of self. But please only do this if x > 0 after doing the assignment. If !(x > 0), go to another case.

关于ios - 为什么 switch 语句中不允许使用 `case self > 0: return .positive`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40124019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com