【问题标题】:Swift: switching on enums without a switch statementSwift:在没有 switch 语句的情况下打开枚举
【发布时间】:2015-12-22 20:12:37
【问题描述】:

使用 Optionals,您可以轻松地检查结果,并使用非 nil 或传递 nil,只需一行:

guard x = couldReturnNil() else { return nil }
// After here, x can be used safely. Calling function
// can do the same, so nil gets passed back down the calling stack.

这使得返回类型的错误处理变得容易。我想要的是其他枚举的类似单行。就像 .Fail/.Succeed 的经典示例一样。例如:

enum Result {
    .Fail(String)     // Error message.
    .Succeed(MyType)  // Something to work with.
}

guard let x = couldFail() case .Succeed(let y) else { return x }
// Use y safely here.

现在,这可以像这样以庞大的方式完成:

let x = couldFail()
let y:MyType
switch x {
case .Succeed(let dummy) { y = dummy }
case .Fail: return x
}

我已经在 switch 之外摆弄了各种与 case 语句进行模式匹配的方法,但无济于事。可以使用异常,但枚举关联值的目的之一肯定是启用这样的东西。也许是自定义运算符?也许某些 SmartPerson™ 有建议。

【问题讨论】:

    标签: swift enums switch-statement


    【解决方案1】:

    这样的? guard/case 带模式匹配:

    let x = couldFail()
    guard case let .Succeed(y) = x else { return x }
    // y can safely be used here ...
    

    如果 else-body 中需要 x,那么您必须将其分配给 首先是一个变量。否则单线会做:

    guard case let .Succeed(y) = couldFail() else { return }
    // y can safely be used here ...
    

    【讨论】:

    • 是的,我试图把你的两个陈述塞进一个。但这可能是我们能做的最好的了。尽管如此,与笨重的方式相比,它还是一个巨大的改进。
    • @AndrewDuncan:在保护条件中声明的变量在正文中不可用,所以这是我能找到的最好的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多