swift - 如何使用带有元组模式匹配的 Swift switch 语句来表达 "not equal to"

标签 swift

<分区>

我试图在带有元组的 switch 语句中使用模式匹配来清楚地表达枚举不等于一个特定情况的所有情况。这是我的 switch 语句的简化版本:

switch (source, type, status) {
        case (.cashVoucher, _, .awaitingValidation):
            return cashVoucherAwaitingValidationMessageComponants
        case (.cashVoucher, _, != .awaitingValidation):
            return validatedCashVoucherMessageComponants
        default:
            fatalError("")
        }

由于 != 运算符的错误使用,这显然无法编译,但它可以让您了解我要实现的目标。

我希望第一个案例匹配 .cashVoucher 的来源和 .awaitingValidation 的状态。

我希望第二种情况匹配源 .cashVoucher 和除 .awaitingValidation 之外的任何状态。

到目前为止,我能想到 2 个解决方案,但它们的可读性不如我想要的。我可以简单地列出所有其他状态案例,但总共有 8 个并且变得难以阅读。 Alernativly,我可以只使用 case case (.cashVoucher, _, _): 并且由于 switch case 的顺序,它会做我想要实现的事情,但我的 switch 语句实际上有总共 16 个案例,并且依赖于 switch case 的顺序,在我看来读者更难理解。

那么有什么方法可以使用类似于我上面的 != .awaitingValidation 来表达这一点?

最佳答案

你应该可以这样写:

switch (source, type, status) {
case (.cashVoucher, _, let st) where st == .awaitingValidation:
    return cashVoucherAwaitingValidationMessageComponants
case (.cashVoucher, _, let st) where st != .awaitingValidation:
    return validatedCashVoucherMessageComponants
default:
    fatalError("")
}

因此将元组的第三个值赋给一个常量(这里是st)并使用where来检查是否相等。

关于swift - 如何使用带有元组模式匹配的 Swift switch 语句来表达 "not equal to",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40920633/

相关文章:

swift - URLSessionDataTask 忽略 URLRequest 的 httpMethod 属性

swift - UIView 动画表现怪异

ios - 在 Swift 中创建一个 UIAlertAction

ios - 在 Swift 中,如何将数组中的每个元素设置为 nil?

ios - 在 Swift 中编写一个永远循环的动画

iOS SplitViewController : Show master view when loading in compact width

ios - startMonitoringSignificantLocationChanges 不能快速工作

ios - 无需上路行驶即可测试 GPS 路线追踪器

swift - 重新加载 TableView 时出错(更新前删除行)

iOS:如何检测用户是否订阅了自动续订订阅