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

标签 ios swift enums switch-statement

我正在使用 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/

相关文章:

enums - 我如何构造/解构枚举的枚举?

ios - 生成唯一的 uibutton 标签

ios - 如何使用 ScrollToItem(位于 :) when using a custom collectionView layout to alter cell sizes

ios - 删除核心数据项

ios - AwakeFromNib 没有导出

ios - 使用约束对齐

swift - “链接”仅在 macOS 11.0 或更高版本中可用

arrays - 希望将 EMV 数据解析为 TLV

c# - 如何从 EventLogEntryType 枚举中获取 int 值

c++ - 如何将 C++ 枚举与 UnitTest++ 检查一起使用?